The history of javascript modularization

JS modular development has a long history, early popular namespace development ideas, to later have some modular development specifications, the first is CommonJS (mainly used in NodeJS and browser), later AMD, CMD, UMD, ESM and other specifications have been born. Because JS does not provide a native, language-level modular development mode, but modularity to developers to achieve, so the birth of these specifications, so that JS modular development becomes standard.

CommonJS
  • One module per file;
  • Using exports. Xx =… Module.exports ={} exposes modules;
  • Introduce a module using the require() method;
  • Require () executes synchronously;

The sample

// a.js
let fn=function(msg){
  console.log(msg);
}
exports.outMsg=fn;
//b.js
const a=require('./a.js');
a.outMsg('hello Commonjs'); // hello Commonjs
Copy the code

CommonJS is used in NodeJS environments, not browsers. One module per file; If there are multiple exports, the last export is taken;

AMD

Asynchronous Module Definition

  • Using the define (…). Define a module;
  • Use the require (…). Load a module;
  • Depend on the front, ahead of the execution;

RequireJS is an example implementation from AMD

// Module definition
/ * * *@param Id Module name. If null, the module name defaults to the name of the script requested by the module loader@param Dependencies The module depends on *@param Factory Factory function, the module initializes the execution function or object */
define(id,dependencies,factory)
// For modules, use require to load modules
require([module], callback);Copy the code

CMD

Common Module Definition

  • A file is a module
  • Using the define (…). Define a module (similar to AMD)
  • Use the require (…). Load a module (similar to AMD)

SeaJS is an example of an implementation of CMD:

// CMD 
define(function(require.exports.module){
  var a=require('./a');
  a.sayHello();
  var b=require('./b');// Rely on nearby writing;
  b.sayHello();
  / /...
});
Copy the code

The most significant difference between CMD and AMD is that AMD executes early, while CMD executes late and relies on proximity.

AMD: the process of execution will be all the dependent module front execution, that is, their own code logic before all the execution;

CMD: if require but the entire logic does not use the dependency or does not execute until the logic uses it.

UMD

The full name is Universal Module Definition, and as the name suggests, UMD does a unified job. Webpack packaging code has the UMD option.

This universal module can be used on the server side or the browser side;

It does three main things:

  • Check whether AMD is supported
  • Determine whether CommonJS is supported
  • If none is supported, use global variables

The main code is as follows:

(function (root, factory) {
    // Correspond to the three steps above
    if (typeof define === 'function' && define.amd) {
        // 1. Check whether AMD is supported
        // If the define method is defined and the define method is an AMD specification, then the factory module entity is defined in the DEFINE method with the AMD specification
        define([], factory); // [] is a dependency, and factory is a module entity
    } else if (typeof exports= = ='object') {
        // 2. Check whether CommonJS is supported
        // exports is an object that runs in Node, CommonJS is supported, and module.exports is used to expose the entire module entity
        module.exports = factory();
    } else {
        // 3. If none is supported, use global variables
        // Browser globals (root = window)
        root.returnExports = factory();
  }
}(this.function () {
    // Module Defination
    var sum = function(x, y){
        return x + y;
    }
    var sub = function(x, y){
        return x - y;
    }
    var math = {
        findSum: function(a, b){
            return sum(a,b);
        },
        findSub: function(a, b){
            returnsub(a, b); }}return math;
}));
Copy the code

ES Module (ES6 Module)

The full name of ECMAScript Module

  • Import modules using import;
  • Export module with export;

Example:

// Export the module
export var a='123'; // Export variables
export function fn(){}; // Export the function
export default {name:'p'.age:18} // Export objects; Export cannot export the object directly.
export class Myclass{} // Export class;

Copy the code

ES6 module and Common JS module differences:

CommonJS outputs a copy of a value. The ES6 module outputs references to values;

2. CommonJS modules are loaded at runtime; The ES6 module is a compile-time output interface;

Since the ES6 module is a compile-time output interface, you can do tree shaking;