An overview,

Front-end in the early stage of development is to achieve simple page interaction logic, through script tags to import one JS file after another, there is no modular concept, with the gradual enrichment of website functions, js in the web page has become more and more complex and bloated, The original script label to import a JS file this way can not meet the current Internet development mode, we need team collaboration, module reuse, unit testing and so on a series of complex requirements. This brings great trouble to the multi-person development of large and complex projects, and it is very difficult to cooperate in development and reuse, and of course the efficiency is very low. Java, Python, and even CSS have @import, but inexplicably JS doesn’t have it. With the advent of WEB2.0 era, Ajax technology has been widely used, jQuery and other front-end libraries emerge in an endless stream, and front-end code is expanding day by day. At this time, modular standards will be considered to manage JS. ES6 was solved after the emergence of this problem, but before this, various communities have also appeared a lot of solutions, the most outstanding is widely circulated by everyone has AMD,CMD, CommonJS,UMD, today xiaobian with you to reveal the mystery of several modular solutions.

What is a module

Simply speaking, a project, with modularization, we can more conveniently use other people’s code, improve the coupling degree and reuse rate of the code, want what function, load what module. To use other people’s modules, we need to follow a set of specifications. Before the advent of ES6 modularity, there were many solutions in various communities. The front-end modularity specification was implemented through AMD,CMD, CommonJS,UMD specifications.

  • Encapsulate a complex program into several blocks (files) according to certain rules (specifications) and combine them together
  • The internal data and implementation of a block are private, exposing only interfaces (methods) to communicate with other external modules
  • Securely wrap a module’s code to avoid global contamination
  • Uniquely identifies a module
  • Gracefully expose the module API
  • Easy to use modules

Third, AMD, CMD, CommonJS, ES6 comparison

J Simply put, they are all for use in modular definition. AMD, CMD and CommonJS are modular programming schemes provided in ES5, and import/export is added to the definition in ES6. These specifications are aimed at modularizing JavaScript development, especially on the browser side. At present, the implementation of these specifications can achieve the purpose of browser side modular development.

  • 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
  • The CommonJS Modules/2.0 specification is the standardized output of the module definition in the promotion process of BravoJS
  • For dependent modules, AMD preempts execution, CMD delays execution, but as of RequireJS 2.0, it is possible to delay execution.

4. CommonJS module specification

Nodejs uses CommonJS, a server-side modularization specification that aims to build a javaScript ecosystem outside of the browser environment. Nodejs is a module defined to address javaScript’s scope issues. Each module can be executed in its own namespace. A single file is a module with its own scope. Variables, functions, and classes defined in one file are private and invisible to other files. The main content of the specification is that a module must export external variables or interfaces through module.exports and import the output of other modules into the scope of the current module through the require method, which reads the file and executes, returning the export object. Nodejs applications currently consist of modules that follow the CommonJS specification in server and desktop environments.

  • NodeJS applications are made up of modules that follow the CommonJS module specification
  • CommonJS loads modules synchronously
  • Each file is a module with its own scope
  • Variables, functions, and classes defined in one file are private and invisible to other files
  • The CommonJS specification states that within each module, the module variable represents the current module. This variable is an object, itsexportsAttribute (i.e.,module.exports) is the external interface. Loading a module is actually loading the modulemodule.exportsProperties.

4.1 Module Reference

CommonJS module definition is very simple, mainly divided into three parts: module reference, module definition and module identification

example.js

// Module application
const http = require('http');
var a = require('./a.js');
var b = require('config.js');

// Module definition
var x = 5; 
var addX = function (value) { 
    return value + x; 
};

// Module identifier
module.exports.a = a; 
module.exports.b = b; 
module.exports.x = x; 
module.exports.addX = addX;
Copy the code

Exports module A, b variable x and function addX. Exports property is an object.

4.2 Module Loading

CommonJS loads modules synchronously, with the require method used to load modules

var example = require('./example.js'); 
console.log(example.x);          / / 5
console.log(example.addX(2));    / / 7
Copy the code

4.3 exports and the module exports

For convenience, NodeJS provides an exports variable for each module, pointing to module.exports. Var exports = module.exports; var exports = module.exports; So we can add methods directly to exports objects to represent interfaces that export, just like we did on Module.exports. NodeJS exports exports through module.exports. If you point the exports variable directly to a value, you break the link between exports and module.exports, causing an accident:

// a.js 
exports = function a() {}; 
// b.js 
const a = require('./a.js') A is an empty object
Copy the code

We can change it to theta


// a.js 
exports.x = function() {}; 

// b.js 
const a = require('./a.js') 
// Call the function
a.x()
Copy the code

Note: If you don’t understand everything, it’s easier to just use module.exports

5. AMD module specification

AMD is the canonical output of the RequireJS module definition in the promotion process. It is a concept, and RequireJS is an implementation of this concept, just as JavaScript language is an implementation of the ECMAScript specification. AMD is an organization under which RequireJS is a set of scripting languages. AMD is mainly a set of specifications for the performance of front-end JS. CommonJS is mainly designed for the back-end performance of JS, and it is not suitable for the front-end;

AMD stands for Asynchronous Module Definition. The asynchronous mode is used to load the module, which does not affect the running of the following statements when loading the module.

AMD also uses the require() statement to load modules, but unlike CommonJS, it takes two arguments; Require ([‘ module name ‘], callBack); RequireJs follows the AMD specification;

Vi. CMD module specification

CMD is the abbreviation of Common Module Definition, and it is a set of specification recommended by SEAJS. CMD is also used to load modules asynchronously. Different from AMD, THE loading of CMD is carried out according to the nearest rule, and AMD relies on preloading. CMD will change the module into a string when loading the use of parsing again to know which module depends on;

 

CommonJS is also implemented in the browser. The principle is to define all modules and use id index to easily parse in the browser environment.

An AMD implementation is defined in a closure via the define function, e.g. Define (ID? : String, dependencies? : String [], the factory: the Function | Object);

Where id is the name of the module and is an optional parameter; Dependencied specifies an array of dependent modules. The output of each dependent module is passed to the Factory as a parameter. If no dependencies are specified, default is [“require”, “exports”, “module”]; A factory contains the concrete implementation of a module, which is a function or object; If it is a function, its return value is the module’s output interface or value.

Vii. UMD module specification

UMD is a combination of AMD and CommonJS,AMD for browsers and CommonJS for servers. If you combine the two, you can achieve a cross-platform solution. UMD determines whether AMD (define exists) is supported, and whether AMD modules are used to load modules, and then whether NodeJS modules are supported, or whether NodeJS modules are used, otherwise it hangs in the window when global variables are used. This is also the way many plugin headers are currently written, which is designed to accommodate various modularity options.

(function(window, factory) {
    //amd
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } 
    //umd
    else if (typeof exports= = ='object') { //umd
        module.exports = factory();
    } 
    else {
        window.jeDate = factory();
    }
})(this.function() {... module.. code... })Copy the code