Understand frontend modularization (CommonJs, AMD, and CMD)

Source: Internet
Author: User
There are three front-end module specifications: CommonJs, AMD, and CMD. CommonJs is used on the server, AMD and CMD are used in the browser environment. AMD is the standardized output of modules defined by RequireJS during promotion. CM...

There are three front-end module specifications: CommonJs, AMD, and CMD.

CommonJs is used on the server, AMD and CMD are used in the browser environment.

AMD is the standardized output of modules defined by RequireJS during promotion.

CMD is the standardized output of modules defined by SeaJS during promotion.

AMD: Early execution (asynchronous loading: dependency first execution) + delayed execution

CMD: delayed execution (running to loading, executed in order)

Module

Function writing

function f1(){    //...}function f2(){    //...}

A module is a file that implements specific functions. Several functions are placed in a file to form a module. Load the file as needed and call the functions in the file.

However, this will cause global variables to be contaminated, and it cannot be ensured that there is no variable name conflict with other modules, and there is no relationship between module members.

Object writing

var module = {  star : 0,  f1 : function (){    //...  },  f2 : function (){    //...  }};module.f1();module.star = 1;

The module is written as an object. All module members are encapsulated in the object. by calling the object attributes, the module members are accessed. However, the module members are also exposed, and the internal status of the module can be modified externally.

Execute function now

var module = (function(){    var star = 0;    var f1 = function (){      console.log('ok');    };    var f2 = function (){      //...    };       return {          f1:f1,          f2:f2       };  })();module.f1();  //okconsole.log(module.star)  //undefined

Internal private variables cannot be accessed externally

CommonJs

CommonJS is the specification of server-side modules and is promoted and used by Node. Due to the complexity of server-side programming, it is difficult to interact with the operating system and other applications without modules. The usage is as follows:

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 CommonJS specifications:

  • A single file is a module. Each module is a separate scope. That is to say, variables defined within the module cannot be read by other modules unless defined as the attribute of the global object.

  • The best way to output module variables is to use the module. exports object.

  • The loading module uses the require method to read and execute a file and return the module. exports object in the file.

Take a closer look at the above Code and you will notice that require is synchronized. The module system needs to synchronously read the module File Content and compile and execute it to obtain the Module Interface.

However, there are many problems on the browser side.

On the browser side, the best and easiest way to load JavaScript is to insert the script tag in the document. However, the script tag is inherently asynchronous, and the traditional CommonJS module cannot be loaded normally in the browser environment.

One solution is to develop a server component, perform static analysis on the module code, and return the module and its dependency list to the browser. This is easy to use, but requires additional components to be installed on the server, so you need to adjust a series of underlying architectures.

Another solution is to use a standard template to encapsulate the module definition:

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

This template Code provides a chance for the module loader to perform static analysis on the module code and dynamically generate a dependency list before the module code is executed.

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

AMD stands for "Asynchronous Module Definition", which means "Asynchronous Module Definition ". Because it is not supported by JavaScript native, the corresponding library function is required for page development using AMD specifications, that is, the well-known RequireJS. In fact, AMD is the standardized output of the module defined by RequireJS during the promotion process.

The module is loaded asynchronously. The module loading does not affect the execution of the subsequent statements. All statements that depend on this module are defined in a callback function. After loading is complete, the callback function will run.

RequireJS mainly solves two problems

  • Multiple js files may have dependencies. The dependent files must be loaded to the browser earlier than the files dependent on them.

  • When Javascript is loaded, the browser stops page rendering. The more files are loaded, the longer the response time of the page is lost.

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; the second parameter callback is the callback function after successful loading. Math. add () is not synchronized with the math module, and the browser will not be suspended.

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

  Define () function

RequireJS defines a function define, which is a global variable used to define the module:

Define (id ?, Dependencies ?, Factory );

Parameter description:

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

  • Dependencies: the array literal of the module ID that the current module depends on.
    The dependency parameter is optional. If this parameter is ignored, it should be ["require", "exports", "module"] by default. However, if the Length attribute of the factory method is less than 3, the loader selects the number of parameters specified by the function Length attribute to call the factory method.

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

Here is an example:

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

  RequireJs example

Require. config is used to define aliases and configure aliases under the paths attribute. Then, use requirejs (parameter 1, parameter 2); parameter 1 is an array, and the name of the module to be referenced is input. The second parameter is a callback function, and the callback function is used to input a variable, replace the introduced module.

Main. js // configure requirejs for the alias. config ({paths: {jquery: 'jquery. min '// can be omitted. js}); // introduce the module. Use the variable $ to represent the jquery module requirejs (['jquery '], function ($) {detail ('body'background .css ('background-color ', 'red ');});

The introduction module can also write only require (). Requirejs defines the module through define (), and the parameters are the same. Methods and variables in this module cannot be accessed externally. Only return is returned.

Math. jsdefine ('Math', ['jquery '], function ($) {// introduce the jquery module return {add: function (x, y) {return x + y ;}};});

Name this module math. js and save it.

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

Main. js introduces the Module Method

CMD

CMD is the Definition of Common Module Definition. The CMD specification is developed in China, just like AMD has requireJS and CMD has a browser to implement SeaJS, the problem to be solved by SeaJS is the same as that of requireJS, except that the module definition method and module loading (which can be said to be running or parsing) are different.

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

Define (function (require, exports, module) {// module code });

Require is a parameter that can be imported into other modules. exports can export some attributes and methods in the module. module is an object, some attributes and methods associated with the current module are stored above.

AMD is a front-end of dependency. when defining a module, it must declare its dependent module;

CMD loads the nearest dependency as needed, and then require only when a module is used:

// Define (function (require, exports, module) {var a = require ('. /A'). doSomething () // skip the 100 rows var B = require ('. /B ') // dependency can be written nearby. doSomething ()//...}) // AMD recommends define (['. /','. /B '], function (a, B) {// dependencies must be written to a at the beginning. doSomething () // 100 rows B are omitted here. doSomething ()...})

  Seajs example

// Define the module myModule. jsdefine (function (require, exports, module) {var $ = require ('jquery. js') $ ('P '). addClass ('active'); exports. data = 1 ;}); // load module seajs. use (['mymodule. js'], function (my) {var star = my. data; console. log (star); // 1 });

The above is a detailed description of frontend modularization (CommonJs, AMD, and CMD). For more information, see other related articles in the first PHP community!

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: info-contact@alibabacloud.com 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.