commonjs,amd,cmd,es6--02

Source: Internet
Author: User

First, CommonJS
node. JS is the main practitioner of the COMMONJS specification, and it has four important environment variables to support the modular implementation: module, exports, require, global. When actually used, use Module.exports to define the interface of the external output of the current module (it is not recommended to use exports directly), load the module with require.
Defining the module Math.js
var basicnum = 0;
function Add (A, b) {
return a + B;
}
Module.exports = {//write here a function, a variable that requires outward exposure
Add:add,
Basicnum:basicnum
}

When referencing a custom module, the parameter contains a path that can be omitted. js
var math = require ('./math ');
Math.add (2, 5);

//reference Core module, no path required
var http = require (' http ');
Http.createservice (...). Listen (3000); The
Commonjs loads the module in a synchronous manner. On the server side, the module files all have local disks and are read very quickly, so there is no problem with this. But on the browser side, limited to network reasons, a more reasonable scenario is to use asynchronous loading. The
II, AMD, and Require.js
AMD specifications load 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. This article introduces the modularity of the AMD specification with Require.js: Specify the reference path with Require.config (), define the module with the define (), and load the module with the Require ().
First we need to introduce the Require.js file and a portal file main.js. Configure Require.config () in Main.js and specify the base modules used in the project. The
/ page introduces require.js and Main.js /
<script src= "js/require.js" data-main= "Js/main" ></ Script>

/ main.js Portal File/main module /
//First specify each module path and reference name with config ()
Require.config ({
BaseUrl: "Js/lib",
Paths: {
"jquery": "Jquery.min",//actual path is Js/lib/jquery.min.js
"underscore": "Underscore.min",
}
});
Perform the basic Operation
require (["jquery", "underscore"],function ($, ) {
//some code here
});
When referencing a module, we place the module name in [] as the first parameter of Reqiure (), and if the modules we define depend on other modules, then we need to place them in [] as the first parameter of define ().
//define Math.js module
define (function () {
var basicnum = 0;
var add = function (x, y) {
return x + y;
};
Return {
Add:add,
Basicnum:basicnum
};
});
//Define a module that relies on underscore.js
define ([' Underscore '],function (
) {
var classify = function (list) {
_. CountBy (list,function (num) {
return num > 30? ' Old ': ' Young ';
})
};
Return {
classify:classify
};
})

Referencing the module, placing the module within []
Require ([' jquery ', ' Math '],function ($, math) {
var sum = Math.add (10,20);
$ ("#sum"). html (sum);
});
Third, CMD and sea.js
Require.js the code within the module is loaded and executed at the first time when the dependent module is declared:
Define (["A", "B", "C", "D", "E", "F"], function (A, B, C, D, E, f) {
is equal to the first declaration and initialization of all modules to be used
if (false) {
Even though it didn't work for a module B, B was executed in advance.
B.foo ()
}
});
CMD is another JS modular scheme, and it is similar to AMD, the difference is that AMD respected the reliance on pre-and early-execution, CMD respected near-dependency, deferred execution. This specification is actually produced in the process of sea.js promotion.
/ AMD notation /
Define (["A", "B", "C", "D", "E", "F"], function (A, B, C, D, E, f) {
is equal to the first declaration and initialization of all modules to be used
A.dosomething ();
if (false) {
Even though it didn't work for a module B, B was executed in advance.
B.dosomething ()
}
});

/ cmd notation /
Define (function (Require, exports, module) {
var a = require ('./a '); DECLARE when necessary
A.dosomething ();
if (false) {
var B = require ('./b ');
B.dosomething ();
}
});

/ sea.js /
//define Module Math.js
Define (function (Require, exports, module) {
var $ = require (' Jquery.js ');
var add = function (A, b) {
return a+b;
}
Exports.add = add;
});
//Load Module
seajs.use ([' math.js '), function (math) {
var sum = math.add (1+2);
}); The
Four, ES6 module
ES6 implements the module function at the language standard level, and is implemented fairly simply, and is designed to be a common module solution for browsers and servers. Its module functions are composed of two commands: Export and import. The Export command is used to specify the external interface of the module, and the Import command is used to enter functionality provided by other modules.
/ Define module Math.js /
var basicnum = 0;
var add = function (A, b) {
return a + b;
};
Export {basicnum, add};

/ Reference Module /
Import {basicnum, add} from './math ';
function test (ele) {
Ele.textcontent = Add (+ basicnum);
}
As the example above shows, when using the import command, the user needs to know the name of the variable or function to be loaded. In fact, ES6 also provides the export default command, which specifies the defaults for the module, and the corresponding import statement does not require curly braces. This is more akin to the ADM citation.
/ Export Default /
Defining the output
Export Default {basicnum, add};
Introduced
Import math from './math ';
function test (ele) {
Ele.textcontent = Math.add (+ math.basicnum);
}
The ES6 module is not an object, and the import command is parsed statically by the JavaScript engine, which introduces the module code at compile time rather than loading it at runtime, so conditional loading cannot be implemented. Because of this, it makes static analysis possible.
Five, ES6 module and CommonJS module difference

    1. The CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value.

The CommonJS module outputs a copy of the value, that is, once a value is output, changes within the module do not affect this value.
The operating mechanism of the ES6 module is different from that of CommonJS. JS engine when the script static analysis, encountered the module load command import, will generate a read-only reference. Wait until the script is actually executed, and then, based on this read-only reference, go to the module that is loaded to fetch the value. In other words, the import of ES6 is a bit like the "symbolic connection" of a Unix system, where the original value changes and the value of the import load changes. Therefore, the ES6 module is a dynamic reference, and the value is not cached, and the variables inside the module are bound to the module in which it resides.

    1. The CommonJS module is run-time loaded, and the ES6 module is the compile-time output interface.

Runtime loading: The CommonJS module is the object, which is to load the entire module first, generate an object, and then read the method from above the object, which is called "Runtime Load".

Compile-time Load: The ES6 module is not an object, but instead explicitly specifies the output code through the Export command, which takes the form of a static command when import. That is, you can specify that an output value be loaded at import instead of loading the entire module, which is called compile-time loading.

CommonJS loads an object (that is, the Module.exports property) that is generated only when the script finishes running. While the ES6 module is not an object, its external interface is just a static definition that is generated during the static parsing phase of the code.

commonjs,amd,cmd,es6--02

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.