Front-end modularity (COMMONJS,AMD and CMD)

Source: Internet
Author: User
Tags aliases

There are three types of front-end module specifications: Commonjs,amd and CMD.
Commonjs used on the server side, AMD and CMD in the browser environment
AMD is the normalized output of the module defined by REQUIREJS during the promotion process.
CMD is the normalized output of the module defined by SEAJS in the process of generalization.
AMD: Early Execution (asynchronous load: Dependency first) + deferred execution
CMD: Deferred execution (run to need to load, executed in order)

Module
    • function notation
  function f1(){    //...  }  function f2(){    //...  }

A module is a file that implements a particular function, and a module is formed by placing several functions in a file. Load this file when needed, and call the function in it.
However, doing so pollutes the global variables, and there is no guarantee that the variable name conflicts with other modules will not occur, and that there is no relationship between the module members.

    • Object wording
      var module = {    star : 0,    f1 : function (){      //...    },    f2 : function (){      //...    }  }; module.f1(); module.star = 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 () {var star = 0; var f1 = function (console.log ( ' OK ');    }; var F2 = function (//...};  return {f1:f1, f2:f2}; })(); module.f1 (); //ok console.log (module.star ) //undefined            

External cannot access internal private variables

CommonJs

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 (functionRequire, 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 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

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 () //here omit 100 lines var b = require ( './b ') //Reliance can be written near B.dosomething () //...}) //AMD The default recommendation is define ([ './b ') , function (a, b) {//dependency must be written in the first place a.dosomething () //here omit 100 rows b.dosomething () ...})  
Seajs Use Example
// 定义模块  myModule.jsdefine(function(require, exports, module) {  var $ = require(‘jquery.js‘) $(‘div‘).addClass(‘active‘); exports.data = 1;});// 加载模块seajs.use([‘myModule.js‘], function(my){ var star= my.data; console.log(star); //1});

Front-end modularity (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: 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.