Front-end development has been emphasizing JS modularization, a function as a module to develop, JS itself does not have the function of a module. The main modular specifications in JS are:
- AMD, Asynchronous Module Definition: this specification can load or rely on other modules asynchronously, and require.js follows the AMD specification.
- CMD, Common Module Definition, CMD depends on nearby, require when used. The CMD specification is followed by the sea-js written by Yubo.
- CommonJS, NodeJS uses CommonJS.
- UMD, common module definition, UMD specification compatible with AMD and CommonJs.
AMD specification
The AMD specification defines only one function, “define”, which is a global variable. The function is described as:
// '? 'Indicates that this parameter is optional define(ID? , dependencies? , callback);Copy the code
- Id, a string, specifies the name of the module. If this parameter is not provided, the name of the module should default to the name of the specified script requested by the module loader. If provided, the module name must be “top-level” and absolute (relative names are not allowed).
- Dependencies, which is an array that specifies the array of modules that the module depends on. The dependencies execute in turn, and the results of the executions should be passed to the callback as arguments, in order of position in the dependency module array.
- Factory, which depends on the callback function or object after the module has successfully loaded. If it is a function, it should be executed only once. If it is an object, the object should be the output value of the module.
The AMD specification defines three special dependency keywords. If “require”,”exports”, or “module” appears in the dependency list, the argument should be resolved as a CommonJS module specification free variable. Defaults to [“require”, “exports”, “module”] if dependencies are not passed. However, if factory has less than 3 parameters, the loader chooses to call Factory with the number of parameters specified by the function.
AMD defines modules:
// We need to specify all the dependencies (deP) when declaring the module and pass them to the factory as parameters.'jquery'], factory($) {
return {
myMethod: function() {
console.log('AMD specification'); }}; })Copy the code
A module definition using Simplified CommonJS Wrapping:
define(function (require, exports, module) {
var a = require('a'),
b = require('b');
exports.action = function () {};
};
})
Copy the code
CMD specification
CMD is the standard recommended by SEAJS, while CMD relies on proximity and requires when used. It is written as follows:
// define(factory) define(function(require, exports, module) {
var a = require('a');
a.hello();
});
Copy the code
Both AMD and CMD load modules asynchronously. The biggest difference is when to execute dependent modules, not how to load them.
- AMD relies on front, ahead of time, rely on modules at a glance;
- CMD dependencies are nearby and load all dependent modules in parallel, but do not execute the module immediately until the corresponding REQUIRE statement. CMD therefore needs to extract the dependent module from factory.tostring (), which results in a longer wait time, and in fact a negligible parsing time for the module.
CommonJS specification
NodeJS module system is implemented according to CommonJS specification. CommonJS is designed for the back-end performance of JS. The API that implements the CommonJS specification loads modules synchronously, because the loading of modules on the server side is usually from the local disk, and the loading speed is very fast, unlike the client side which needs to send a request to load, which may cause ‘suspended animation’.
CommonJS defines modules as:
- Module reference: Used to introduce external modules
- Module definitions: Methods or variables used to export the current module, unique export
- Module identifier (Module) : The Module object represents the module itself
//add.js
exports.add = function(x, y){
return x+y;
};
//main.js
var math = require('add');
exports.add = function(n){
return math.add(100, n);
};
Copy the code
Browserify(Browserify.org/) is currently the most commonly used CommonJS format conversion tool, capable of converting CommonJS specification code into browser-executable code.
While Node follows the CommonJS specification, there are some trade-offs and some new additions.
UMD (Common Module Specification)
The UMD specification is compatible with AMD and CommonJs.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object'Module. Exports = factory(require() {// Node, CommonJS, etc. Module. Exports = factory(require()'jquery'));
} else{// Browser global variable (root = window) root.returnexports = factory(root.jquery); } }(this,function ($) {
function add() {}; // Expose public methodsreturn {
add: add
};
}));
Copy the code
ES6 modular
- The ES6 module is designed to be as static as possible, so that the dependencies of the module, as well as the input and output variables, can be determined at compile time. Require is the CommonJS syntax, and CommonJS modules are objects that must look for object properties when typed.
/ / CommonJS modulelet { stat, exists, readFile } = require('fs');
Copy the code
Commonjs: Load the fs module as a whole (load all the fs methods), generate an object “_fs”, and then read three methods from that object. This is called “runtime load”, because this object is only available at runtime and cannot be static at compile time.
The ES6 module is not an object, but displays the specified output code through the export command, followed by input through import. ES6 modules are loaded at compile time: dependencies between modules are determined by static analysis before they are run (that is, at compile time).
// Load from fsstat, exists, readThe other methods are not loaded. This is compile-time loading, also known as static loading import {stat, exists, readFile } from 'fs';
Copy the code
- ES6 modules automatically adopt strict mode, whether or not you add “Use strict” to the module header; .
- ES6 uses import and export to achieve modularity. Import is used to import other modules, export is used to output external interfaces, which can be variables, functions and classes.
Export keyword
A module is an independent file. All variables inside the file are not available externally. If you want outsiders to be able to read a variable inside a module, you must use the export keyword to output that variable.
Export can output variables, functions, and classes, but cannot directly output values. Otherwise, an error will be reported. The export command specifies an external interface and must establish a one-to-one correspondence with variables inside the module.
const sum = function(a, b) {
return a+b;
}
const minus = function(a, b) {
returna-b; } // There can be more than one moduleexportCommand statement.exportThe {sum} // as keyword is used to rename variablesexport {
minus as reduce
}
Copy the code
Note: export cannot output values, and the variable function or class names it outputs should be placed in “{}”
Export the default command
Export default Specifies the default output for a module. Each module can have only one default output. Export default is to output a variable named default, and the system allows you to call it any name you want.
export default sum(a, b) {
return a+b;
}
Copy the code
import:
- The interface that loads export output using import must be wrapped with {}
import {sum as add, reduce } from './index.js';
Copy the code
- The interface to load export default output using import
// import sum from'./index.js'; Import default as foo from'./index.js';
Copy the code
Note:
- Import is only imported once, and no matter how many times you introduce it to improve it, import is automatically promoted to the top, executed first
- Because import is executed statically, you cannot use expressions and variables, which are syntactic structures that are only available at run time.
- When looping, ES6 modules are referenced dynamically. As long as there is a reference between the two modules, the code can execute.