Front-end modularity for some understanding of-COMMONJS, AMD and CMD

Source: Internet
Author: User

---restore content starts---

There are three types of front-end modular Specifications: Commonjs\amd\cmd

    • For server-side
    • For the browser environment, is the REQUIREJS in the promotion process of the module definition of normalized output
    • Early execution (asynchronous load: Dependency first execution) + deferred execution
    • Seajs the normalized output of module definition in the process of generalization
    • Deferred execution (run to load, executed in sequence)
Modules-Files that implement special features
    • function notation
function F1 () {    //...   }function  f2 () {    //...}
    • Object wording

Since functional notation can contaminate global variables, variable name collisions can occur, so we need variable notation

var module = {    0,    function() {        //...     },     function () {        //...      = 1;

The module is written as an object, and the module members are encapsulated in the object, accessed using the module members by invoking the object properties. But also exposes the module members, external can modify the internal state of the module

Execute function immediately

varmodule = (function(){    varStar = 0; varF1 =function() {Console.log ("OK");    }; varF2 =function() {        //...    }; return{f1:f1, f2:f2};}) (); Module.f1 (); //OKConsole.log (
    • External cannot access internal private variables

COMMONJS is the specification of server-side modules, which are used by node for promotion. Because of the complexity of server-side programming, it is difficult to interact with the operating system and other applications without modules. Here's how to use it:

math.jsexports.add = function() {    var sum = 0, i = 0, args = arguments, l = args.length;    while (i < l) {      sum += args[i++];    }    return sum;};increment.jsvar add = require(‘math‘).add;exports.increment = function(val) {    return add(val, 1);};index.jsvar increment = require(‘increment‘).increment;var a = increment(1); //2

According to the COMMONJS specification:

    • A separate file is a module. Each module is a separate scope, meaning that variables defined inside the module cannot be read by other modules unless they are defined as global properties of the object.
    • The best way to output module variables is to use module.exports objects.

    • The load module uses require a method that reads a file and executes it, returning an object inside the file module.exports

Look closely at the code above and you'll notice that require it's synchronized. The module system needs to read the module file contents synchronously and compile execution to get the module interface.
However, there are a lot of problems with the browser side.

On the browser side, the best and easiest way to load JavaScript is to document insert <script> tags in. But script tags are inherently asynchronous, and traditional CommonJS modules do not load properly in a browser environment.

One of the solutions is to develop a server-side component that makes static analysis of the module code and returns the module to the browser side, along with its dependency list. This works well, but requires the server to install additional components and therefore adjusts a series of underlying architectures.

Another approach is to encapsulate the module definition with a standard set of templates:

define(function(require, exports, module) {  // The module code goes here});

The template code provides the opportunity for the module loader to perform static analysis of the module code and dynamically generate dependency lists before the module code executes.

math.jsdefine(function(require, exports, module) {  exports.add = function() {    var sum = 0, i = 0, args = arguments, l = args.length;    while (i < l) {      sum += args[i++];    }    return sum;  };});increment.jsdefine(function(require, exports, module) {  var add = require(‘math‘).add;  exports.increment = function(val) {    return add(val, 1);  };});index.jsdefine(function(require, exports, module) {  var inc = require(‘increment‘).increment;  inc(1); // 2});

AMD is "Asynchronous Module Definition" the abbreviation that means "async module definition". Because it is not JavaScript native support, the use of the AMD Specification for page development requires the corresponding library functions, that RequireJS is, the famous, in fact, AMD is RequireJS in the promotion process of the module defined by the normalized output

It loads the module asynchronously, and the module's load does not affect the execution of the statement behind it. All statements that rely on this module are defined in a callback function that will not run until the load is complete.

RequireJSSolve two major problems

    • Multiple JS files may have dependencies, the dependent files need to be loaded into the browser earlier than the files that depend on it
    • JS load when the browser will stop the page rendering, loading more files, the page lost response time longer

Requirejs also uses the Require () statement to load the module, but unlike COMMONJS, it requires two parameters:

The first parameter, [module], is an array in which the member is the module to be loaded, and the second parameter, callback, is the callback function after the load succeeds. Math.add () is not synchronized with the math module, and the browser does not take place in animation.

require([module], callback);require([increment‘], function (increment) {    increment.add(1);});
Define () function

RequireJSDefines a function define , which is a global variable used to define the module:
define(id?, dependencies?, factory);
Parameter description:

    • ID: Refers to the name of the module in the definition, optional; If the parameter is not provided, the module name should default to the name of the specified script requested by the module loader. If this argument is provided, the module name must be "top-level" and absolute (relative names are not allowed).

    • Dependent dependencies: is an array literal that is dependent on the current module and that has been identified by the module definition.
      The dependent parameter is optional, and if this parameter is omitted, it should default to ["Require", "exports", "module"]. However, if the length attribute of the factory method is less than 3, the loader chooses to call the factory method with the number of arguments specified by the function's Length property.

    • Factory method Factory, the module initializes the function or object to execute. If it is a function, it should only be executed once. If it is an object, this object should be the output value of the module.

You want to give me a lift? Look:

define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {       exports.verb = function() {           return beta.verb();           //Or:           return require("beta").verb();       }   });
Requirejs Use Example

require.configis used to define aliases, configure aliases under the Paths property. Then pass requirejs (parameter one, parameter two); parameter one is an array, passing in the module name we need to reference, the second parameter is a callback function, the callback function passes in a variable, instead of the module just introduced.

main.js//别名配置requirejs.config({    paths: {        jquery: ‘jquery.min‘ //可以省略.js    }});//引入模块,用变量$表示jquery模块requirejs([‘jquery‘], function ($) {    $(‘body‘).css(‘background-color‘,‘red‘);});

The Introduction module can also be written only require() . requirejsby define() defining the module, define the parameters on the same. Outside of the methods and variables within this module is inaccessible, only by return returning.

math.jsdefine(‘math‘,[‘jquery‘], function ($) {//引入jQuery模块    return {        add: function(x,y){            return x + y;        }    };});

Name the module save as Math.js.

require([‘jquery‘,‘math‘], function ($,math) {    console.log(math.add(10,100));//110});

Main.js Introduction Module method


CMD is the Common Module Definition Universal module definition, the CMD specification is developed at home, like AMD has a requireJS , CMD has a browser implementation SeaJS , SeaJS to solve the problem and the requireJS same, just in the module definition mode and module loading (can be said to run, resolution) is different in timing.

In the CMD specification, a module is a file. The code is written in the following format:

define(function(require, exports, module) {  // 模块代码});

requireis a parameter that can be imported into another module, but exports it is possible to export some properties and methods within the module; module it is an object that stores some properties and methods associated with the current module.

AMD is a dependency front, and it is necessary to declare its dependent modules when defining a module;
CMD is load dependent on demand nearest, only when using a module to go to require:

// CMDdefine(function(require, exports, module) {  var a = require(‘./a‘)  a.doSomething()  // 此处略去 100 行  var b = require(‘./b‘) // 依赖可以就近书写  b.doSomething()  // ... })// AMD 默认推荐的是define([‘./a‘, ‘./b‘], function(a, b) { // 依赖必须一开始就写好  a.doSomething()  // 此处略去 100 行  b.doSomething()  ...})
Seajs Use Example
// 定义模块  myModule.jsdefine(function(require, exports, module) {  var $ = require(‘jquery.js‘)  $(‘div‘).addClass(‘active‘); = 1;});// 加载模块seajs.use([‘myModule.js‘], function(my){    var star=;    console.log(star);  //1});

This "front-end modularity: COMMONJS,AMD and CDM" is primarily a personal summary of the following articles, thanks to the sharing of these old drivers.
Front-end modularity
Detailed JavaScript Modular Development
JavaScript Modular Programming
From CommonJS to Sea.js

---restore content ends---

Some of the front-end modularity understand-commonjs, AMD, and CMD

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.