JavaScript modular

Standardizing the module definition and loading mechanism of JavaScript reduces the threshold of learning and using various frameworks. It can define and use modules in a unified way, improve development efficiency and reduce application maintenance costs.

  • Naming conflicts
  • File is dependent on

differences

  • AMD and CMD:
    • AMD is the canonical output of RequireJS’s module definition in its promotion process.
    • CMD is the normalized output of SeaJS module definitions during the roll-out process.
    • CMD advocates dependency nearby, AMD advocates dependency front.
  • ES with CommonJS Module:
    • CommonJS modules are objects that are loaded at run time. The run time mounts modules on exports (loads all of the modules) and loads modules to find object properties.
    • ES Module is not an object. It uses export to display specified output and import to input. This method is loaded at compile time, which generates a read-only reference when an import is encountered. The loaded module is evaluated at runtime based on this reference. So don’t load all of the module’s methods, just take what you need.
    • The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value.
    • The CommonJS module is run time loaded, and the ES6 module is compile time output interface
  • CommonJS with AMD/CMD:
    • AMD/CMD is a browser-side solution to CommonJS.
    • CommonJS is synchronous loading (code is local, load time is basically equal to disk read time).
    • AMD/CMD is loaded asynchronously (browsers must do this, code is on the server side)
  • UMD with AMD/CMD
    • UMD (Universal Module Definition) is a cross platform solution combining AMD and CommonJS.
    • AMD modules evolve on a browser-first basis, loading modules asynchronously.
    • The CommonJS module follows the server first principle of synchronous loading and does not require unwrapped modules.
    • UMD determines whether any module (exports) that supports Node.js exists and uses node.js module mode if it does. Then check whether AMD is supported (define exists). If yes, load the module in AMD mode.

usage

  • CommonJS
    • Exports use module.exports and can be exports. Is to hang properties on this object. Exports refers to module.exports = module.exports
    • Load modules using require(‘ XXX ‘). Both relative and absolute paths are acceptable. The default reference is js, and you can leave out the.js suffix
// commonjs
module.exports.add = function add(params) {
    return ++params;
}
exports.sub = function sub(params) {
    return --params;
}
// index.js
var common = require('./commonjs');
console.log(common.sub(1));
console.log(common.add(1));
Copy the code
  • AMD/RequireJS
    • Define module: define(ID? , dependencies? , factory)
      • Dependencies have three defaults, namely “require”, “exports”, “module”. The number of orders depends on the situation
      • If ignored, factory defaults to these three incoming arguments
      • Id is usually not passed, the default is the file name
    • Require ([module], factory)
// a.js
define(["b"."require"."exports"].function(b, require, exports) {
    console.log("A. s execution"); console.log(b); // Exports, module.exports,return
    exports.a = function() {
        return require("b");
    }
})
// b.js
define(function() {
    console.log('b.j s execution');
    console.log(require);
    console.log(exports);
    console.log(module);
    return 'b'; }}}}}}}}}}}}}}}}}}}function(require, exports, module) {
    console.log('index. Js execution');
    var a = require('a');
    var b = require('b');
})
// index.js
require(['a'.'b'].function(a, b) {
    console.log('index. Js execution');
})
Copy the code
  • CMD/SeaJS
    • Define module: Define (Factory)
      • Require, exports, module arguments in the same order
      • Exports, module.exports, return
      • Unlike requirejs, which returns undefined, it returns {} if not exposed
    • Load the module: require
    • The defining module does not require column dependencies, which it analyzes by calling factory’s toString method for a regular match
    • Pre-download, delayed execution
// a.js
define(function(require, exports, module) {
    console.log(A. 's execution');
    console.log(require);
    console.log(exports);
    console.log(module);
})
// b.js
define(function(require, module, exports) {
    console.log('b.j s execution');
    console.log(require);
    console.log(exports);
    console.log(module);
})
// index.js
define(function(require) {
    var a = require('a');
    var b = require('b');
    console.log(a);
    console.log(b);
})
Copy the code
  • ES Module
    • Output/export
    • The input/import
    • The input module variable is not reassigned; it is just a readable reference, but the property can be overwritten
/ / an error 1export1; // error 2 const m = 1;exportm; // There is a one-to-one correspondence between the interface name and the module's internal variablesexportconst m = 1; // const m = 1;export{ m }; // const m = 1;export { m as module };
Copy the code
// Similar to object deconstruction // module.jsexportconst m = 1; // index.js // note that m corresponds to import {m} from from the interface name of the loaded module'./module';
// 若是想为输入的变量取名
import { m as m1 }  './module'; // It is important to note that import is compiled, so it cannot be loaded dynamically. because'a' + 'b'Values are fetched at run time, which is after compile time import {'a' + 'b' } from './module'; // If you just want to run the loaded module, it is worth noting that even if you load it twice, you only run the import once'./module';
// 整体加载
import * as module from './module';
Copy the code
  • Conclusion:
The difference between a Es modular commonJS AMD
Can be used on server or browser Server and browser The service side The browser
When module dependencies are determined (i.e., when modules are loaded) Compile time The runtime The runtime
Design idea Try to be as static as possible
Is a module an object? not is
Whether the module is loaded as a whole (that is, all methods of loading) no is
Whether it is dynamically updated (i.e., through the interface, the value can be retrieved in real time within the module) Is. The ES Module prints references to values It isn’t. The commonJS module outputs a copy of the value, with no dynamic updates
Whether a module variable is read-only V is. Reason: The module variable entered by ES6 is just a “symbolic link”, so this variable is read-only and reassigning it will report an error.
  • CommonJS modules are objects that load modules as a whole (that is, all methods loaded)

  • An ES6 module is not an object. Instead, it explicitly specifies the output code through the export command, which is then input through the import command.

  • The export command specifies the external interface and must establish a one-to-one relationship with variables inside the module

  • The interface output by the export statement is dynamically bound to its corresponding value, that is, through this interface, the real-time information inside the module can be obtained

  • Export and import commands can appear anywhere in the module, as long as they are at the top of the module. If you are in block-level scope, an error will be reported because you cannot do static optimization when you are in conditional code blocks, contrary to the design of the ES6 module.

  • The import command is promoted to the top of the module and executed first.