This article brings you the content about why modularization is needed? An introduction to commonly used modular solutions in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Why modularization is needed
Before the emergence of ES6, the JS language itself did not provide modularization capabilities, which brought some problems to development, the most important of which Two problems should be global pollution and dependency management chaos.
// file a.js var name = 'aaa'; var sayName = function() { console.log(name); };
<!-- file index.html --> <script src='xxx/xxx/a.js'></script> <script> sayName(); // 'aaa' // code... var name = 'bbb'; sayName(); // 'bbb' </script>
In the above code, we called the sayName function provided by a.js twice and output different results. Obviously, this is because both files have assigned values to the variable name, so they cause each other had an impact. Of course, we can be careful not to define existing variable names when writing code, but when a page references a dozen files with several hundred lines, it is obviously not realistic to remember all the variables that have been defined.
// file a.js var name = getName(); var sayName = function() { console.log(name) };
// file b.js var getName = function() { return 'timo'; };
<script src='xxx/xxx/b.js'></script> <script src='xxx/xxx/a.js'></script> <script> sayName(); // 'timo' </script>
<script src='xxx/xxx/a.js'></script> <script src='xxx/xxx/b.js'></script> // Uncaught ReferenceError: getName is not defined
The above code shows that when multiple files have dependencies, we need to ensure the order in which they are introduced, so as to ensure that when running a certain file, its dependencies have been loaded in advance. It is conceivable that in the face of larger files, project, the more dependencies we need to deal with, which is cumbersome and error-prone.
In order to solve these problems, many specifications have emerged in the community that provide modular capabilities for the JS language. With the help of these specifications, our development can be made more convenient and safer.
Common modularization solutions
CommonJS is one of the modularization solutions proposed by the community, and Node.js follows this set plan.
// file a.js var obj = { sayHi: function() { console.log('I am timo'); }; }; module.exports obj;
// file b.js var Obj = require('xxx/xxx/a.js'); Obj.sayHi(); // 'I am timo'
In the above code, file a.js is the provider of the module, and file b.js is the caller of the module.
Each file is a module;
provided within the modulemodule Object, representing the current module;
The module uses exports to expose its own functions/objects/variables, etc.;
The module imports other modules through the require() method; the specifications of
CommonJS are simply the above 4 items. You can understand it by referring to the examples in the basic writing method. , in actual implementation, although Node.js follows the CommonJS specification, it still makes some adjustments to it.
AMD is one of the modular specifications, and RequireJS follows this set of specifications.
// file a.js define('module', ['m', './xxx/n.js'], function() { // code... })
In the above code, the file a.js exports the module;
In AMD, the exposed module uses define Function
define(moduleName, [], callback);
As shown in the above code, the define function has three parameters
moduleName. This parameter can be omitted, indicating the name of the module. Generally, it has little effect
['name1', 'name2'], the second parameter is an array, indicating other modules that the current module depends on. If there are no dependent modules, this parameter can be omitted
callback, the third parameter is a required parameter, it is a callback function, the inside is the relevant code of the current module
Features of ADM It is dependency front-loading. This is the biggest difference between the ADM specification and the CMD specification to be introduced next. Dependency front-loading means: before running the callback of the currently loaded module, all dependent packages will be loaded first, which is the third step of the define function. The dependent packages specified in the two parameters.
define(function(require, exports, module) { var a = require('./a') a.doSomething(); // code... var b = require('./b') // code... })
The above code is the basic writing method of the CMD specification export module;
It can be seen from the writing method It turns out that the writing method of CMD is very similar to that of AMD. The main difference is the difference in dependency loading timing. As mentioned above, AMD is dependent on front-end, while the CMD specification advocates the proximity principle. Simply put, dependencies are not loaded before the module is run. , during the running of the module, when a certain dependency is needed, load it again.
When CommonJS, AMD, and CMD are in parallel, a solution is needed that is compatible with them, so that when we develop, we no longer need to consider the specifications followed by dependent modules. , and the emergence of UMD is to solve this problem.
(function (root, factory) { if (typeof define === 'function' && define.amd) { //AMD define(['jquery'], factory); } else if (typeof exports === 'object') { //Node, CommonJS之类的 module.exports = factory(require('jquery')); } else { //浏览器全局变量(root 即 window) root.returnExports = factory(root.jQuery); } }(this, function ($) { //方法 function myFunc(){}; //暴露公共方法 return myFunc; }));
The above code is the basic writing method of UMD. As can be seen from the code, it can support both the CommonJS specification and the AMD specification.
The above introduces CommonJS, AMD, CMD and UMD respectively. They are all contributions of the community to the modularization of JS. The fundamental reason for the emergence of this specification is the JS language. It has no modularity capabilities. At present, the latest language specification ES6 of JS has added modularity capabilities to JS. JS’s own modularization solution can completely replace the various specifications currently proposed by the community, and can Commonly used on the browser side and Node side.
The modularization capability in ES6 consists of two commands: export and import. The export command is used to specify the external interface of the module. The import command is used to import functions provided by other modules.
A file in ES6 is a module. The variables/functions inside the module are inaccessible from the outside. If you want to expose the internal functions/variables to other modules, To use it, you need to export it through the export command
// file a.js export let a = 1; export let b = 2; export let c = 3;
// file b.js let a = 1; let b = 2; let c = 3; export {a, b, c}
// file c.js export let add = (a, b) => { return a + b; };
上面三个文件的代码,都是通过export命令导出模块内容的示例,其中a.js文件和b.js文件都是导出模块中的变量,作用完全一致但写法不同,一般我们更推荐b.js文件中的写法,原因是这种写法能够在文件最底部清楚地知道当前模块都导出了哪些变量。
模块通过export命令导出变量/函数等,是为了让其他模块能够导入去使用,在ES6中,文件导入其他模块是通过import命令进行的
// file d.js import {a, b, c} from './a.js';
上面的代码中,我们引入了a.js文件中的变量a、b、c,import在引入其他模块内的函数/变量时,必须与原模块所暴露出来的函数名/变量名一一对应。
同时,import命令引入的值是只读的,如果尝试对其进行修改,则会报错
import {a} d from './a.js'; a = 2; // Syntax Error : 'a' is read-only;
从上面import的介绍可以看到,当需要引入其他模块时,需要知道此模块暴露出的变量名/函数名才可以,这显然有些麻烦,因此ES6还提供了一个import default命令
// file a.js let add = (a, b) => { return a+b }; export default add;
// file b.js import Add from './a.js'; Add(1, 2); // 3
上面的代码中,a.js通过export default命令导出了add函数,在b.js文件中引入时,可以随意指定其名称
export default命令是默认导出的意思,既然是默认导出,显然只能有一个,因此每个模块只能执行一次export default命令,其本质是导出了一个名为default的变量或函数。
The above is the detailed content of Why is modularity needed? Introduction to common modular solutions in js. For more information, please follow other related articles on the PHP Chinese website!