Modularity Background
Javascript programs are small — in the early days, they were mostly used to perform stand-alone scripting tasks that provided some interaction where your Web page needed it, so you generally didn’t need much scripting. Over the years, we now have complex programs that run lots of Javascript scripts, and some that are used in other environments. So in recent years, we need to consider a mechanism for breaking up JavaScript programs into separate modules that can be imported on demand (from MDN)
Modularity is the problem to be solved
- Load order
- Global pollution
The original way (execute the function immediately)
The Immediately-Invoked Function Expression (IIFE) is used to achieve the goal of not exposing the private member.
var moduleA = (function(mod){
// Other modules are injected as arguments here
var count_a = 0;
function m1() {
/ /...
};
function m2() {
/ /...
}
return {
m1: m1,
m2: m2
}
})(moduleB);
Copy the code
Node.js Modularity mechanism (commonJS)
Node.js module system is implemented by referring to CommonJS specification. In CommonJS, there is a global method require() for loading modules. Suppose you have a math module, math.js, that can be loaded like this.
const math = require('math');
math.add(2.3); / / 5
Copy the code
Here line 2 math.add(2,3) needs to wait until the first line require(‘math’) math.js is loaded, meaning that if it takes too long to load, the entire application will stay there, etc.
AMD
- Asynchronous loading
- Manage dependencies between modules to facilitate code development and maintenance
- Application scenario: The browser environment
- Usage (the require. Js) :
- export
define(function(){return {}});
- The import
Require ([' module name '], function(' module name '){... })
- export
//moduleA.js
define(function() {
return {
a: 1.b: 2}})//b.js
require(['./a.js'].function(moduleA){
console.log(moduleA.a, moduleA.b);
})
Copy the code
CMD
CMD is an improved specification based on AMD, which differs from AMD in the execution timing of dependency modules. CMD is a nearby dependency, while AMD is a front-dependency.
The difference between AMD and CMD
The most obvious difference is the way dependencies are treated in module definition
- AMD advocates dependency preloading, declaring the module it depends on when defining a module
- CMD advocates proximity, requiring only when a module is needed
The biggest difference between AMD and CMD is the execution timing of dependent modules
ESM(ES6 Module)
- According to the need to load
- Import and export commands can only be at the top of the module, not in code blocks (e.g., if statements), and import() statements can be loaded asynchronously and dynamically on demand in code blocks
- Applicable environment: Browser
- Use:
/ / export
export const a = 1;
export default {
a: 1
}
/ / import
import { a } from './a.js'
import moduleA from './a.js'
Copy the code