AMD (RequireJS)
AMD stands for Asynchronous Module Definition. The AMD specification was later implemented as RequireJS by the authors of this draft, so AMD is generally referred to as RequireJS.
RequireJS basic usage
Use define to define a module, and use require to import the defined module.
//a.js
// Define can be passed three parameters, namely string - module name, array - dependent module, function - callback function
define(function(){
return 1;
})
Copy the code
// b.js
// Declare the module to be loaded in the array. It can be the module name, js file path
require(['a'].function(a){
console.log(a);/ / 1
});
Copy the code
RequireJS features For dependent modules, AMD advocates dependency in advance, in advance execution. That is, the dependency modules (arrays) passed in the define method are downloaded and executed at the start.
CMD ( SeaJS )
CMD is the specification for module definition produced by SeaJS in the promotion process. In the module loader of Web browser, SeaJS and RequireJS are called, and the author of SeaJS is Yibo of Ali.
Basic usage of SeaJS
//a.js
/* * define takes factory, which can be a function or an object or a string. * factory is an object or a string. * Define can also accept more than two parameters. The string ID represents the module id, and the array DEps is a module dependency. */
define(function(require, exports, module) {
var$=require('jquery');
exports.setColor = function() {$('body').css('color'.'# 333');
};
});
Copy the code
//b.js
// Declare the module to be loaded in the array. It can be the module name, js file path
seajs.use(['a'].function(a) {$('#el').click(a.setColor);
});
Copy the code
The characteristics of SeaJS
For dependent modules, CMD advocates proximity and delayed execution. That is, dependencies are executed only when required.
CommonJS
The CommonJS specification is proposed by the CommonJS group to compensate for the lack of modular mechanism in JavaScript server. NodeJS and WebPack are implemented based on this specification.
CommonJS basic usage
//a.js
module.exports = function () {
console.log("hello world")}Copy the code
//b.js
var a = require('./a');
a();//"hello world"
/ / or
//a2.js
exports.num = 1;
exports.obj = {xx: 2};
//b2.js
var a2 = require('./a2');
console.log(a2);//{ num: 1, obj: { xx: 2 } }
Copy the code
The characteristics of the CommonJS
- All code runs in the module scope and does not pollute the global scope;
- The module is synchronously loaded, that is, only after the loading is complete, the following operations can be performed;
- The module is cached after the first execution and only returns cached results when reloaded. If you want to execute again, you can clear the cache
- The value returned by require is a copy of the output value, and changes within the module do not affect this value.
ES6 Module
ES6 Module is a Module system specified in ES6. Compared with the specification mentioned above, ES6 Module has more advantages and is expected to become a common Module solution for browsers and servers.
Basic usage of ES6 Module
//a.js
var name = 'lin';
var age = 13;
var job = 'ninja';
export { name, age, job};
Copy the code
//b.js
import { name, age, job} from './a.js';
console.log(name, age, job);// lin 13 ninja
Copy the code
/ / or
//a2.js
export default function () {
console.log('default ');
}
//b2.js
import customName from './a2.js';
customName(); // 'default'
Copy the code
ES6 Module features (compare CommonJS)
- CommonJS Module is loaded at runtime, ES6 Module is output at compile time;
- CommonJS loads the entire Module and loads all interfaces in it. ES6 Module can load one interface separately.
- CommonJS output is a copy of a value, ES6 Module output is a reference to the value, the output Module internal changes will affect the reference change;
- CommonJS this refers to the current Module, ES6 Module this refers to undefined;
ES6 Module is not compatible with browsers at present. Export /import used in Webpack will be converted to CommonJS by Babel.
Conclusion:
- AMD relies on pre-execution (require.js), the syntax is define, require
- CMD relies on nearby, delayed execution (sea.js), syntax is define, seajs.use([],cb)
- CommonJs syntax module.exports=fn or exports.a=1; Introduced by require(‘./a1’)
- The CommonJs module is cached the first time it executes, and only returns cached results when reloaded. Require returns a copy of the output value (shallow copy for reference types).
- Es6 Module syntax export {… }, import … from… , export outputs worthy references.
- NodeJS and WebPack are implemented based on commonJs specification
A few minor problems
- It may exist in the VUE project. We import module B from module A and module B from module C. Then how does the modularization mechanism deal with the scenario where module B is imported several times in A project?
If you require an imported module through commonJS, the first import will be cached, and subsequent imports will take the cached results of the first import. If you import a module using es6 import, then all you import are references to values. So,, import multiple times is in the final package, only hit one and will not be repeated.
- If you have a deeper understanding, you need to use it more first, and then you still need to go through the internal implementation of CommonJS and es6.
One question remains: how do we implement B by importing module A? No modularization
- Copying the code from module A to module B is obviously not feasible, as it would be too much code to be copied
- Create A script tag dynamically and let A import it and execute it. And then I’m going to introduce B
- The ES6 Module is a reference to the exported value. How does this work?
- How to handle repeated imports?
- How are circular references handled?
- .
Summary -Commonjs and ES6 Module differences
- Commonjs is a synchronous import, because it is used in the server, the files are local, synchronous import even if the main thread is blocked, the latter is asynchronous import, because it is used in the browser, you need to download the file, if the use of synchronous import will have a great impact on rendering.
- CommonJS is always a copy of the value when exported, and the imported value does not change even if the exported value changes. If you want to update it, you must import it again.
- ES Module import/export values point to the same memory address. Therefore, the imported value also changes with the exported value.
- ES Module compiles to require/exports.
- An export is a copy of a value, and an export is a reference to a value
- One is synchronous import, one is asynchronous import
Reference: juejin. Cn/post / 684490…
Please point out many of the problems, the use of a lot of articles, difficult is, really understand its internal mechanism and how to achieve? Consider the problem from the module author’s point of view, think more, learn to master the essentials. To implement their own tools.
Code word is not easy, feel ok, give star, your star, is my motivation
github