Front-end modularity scheme: COMMONJS/AMD/CMD/ES6 specification

Source: Internet
Author: User

The modular development method can improve the code reuse rate and facilitate the management of code. Usually a file is a module that has its own scope, exposing only specific variables and functions to the outside. The current popular JS Modular specification has COMMONJS, AMD, cmd and ES6 module system. The evolution of the front-end modularity can be seen in the Nanyi teacher's article. This paper mainly introduces the modular realization mode under each specification.

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.

Define module Math.jsvar basicnum = 0;function Add (A, b) {    return a + b;} Module.exports = {//write here the function that needs to be exposed, the variable    add:add,    basicnum:basicnum}//reference the custom module, the parameter contains the path, can be omitted. Jsvar math = Require ('./math '); Math.add (2, 5);//When referencing the core module, you do not need to take the path var http = require (' http '); Http.createservice (...). Listen (3000);

COMMONJS load 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.

Second, AMD and Require.js

The AMD specification 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. 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.

/** Web page introduces require.js and main.js **/<script src= "js/require.js" data-main= "Js/main" ></script>/** main.js entry file /Main module **///first specify each module path and reference name Require.config ({    baseUrl: "Js/lib",    paths: {        "jquery": "Jquery.min") with config (), The  actual path is js/lib/jquery.min.js        "underscore": "Underscore.min",    }});//Perform 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    };}) Reference module, place 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) {      //equals the first declaration and initialization of all modules to be used    if (false) {        / /Even if a module B is not used, B is executed        B.foo ()    }) in advance;

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) {      //equals to the first declaration and initialization of all modules to be used    A.dosome Thing ();    if (false) {        //Even if a module B is not used, but B is executed in advance        b.dosomething ()    }});/** cmd **/define (function (require, exports, m Odule) {    var a = require ('./a ');//Declare    a.dosomething ()    as required; if (false) {        var b = require ('./b ');        B.dosomething ();    }}); * * sea.js **///definition Module math.jsdefine (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);});
Iv. ES6 Module

ES6 in the language standard level, realizes the module function, and realizes quite simple, aims to become the browser and the server Common module solution. Its module function is composed of two commands: export and import . exportcommands are used to specify the external interface of the module, and import commands are used to enter functionality provided by other modules.

/** definition 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, import when using a command, the user needs to know the name of the variable or function to be loaded. In fact, ES6 also provides a export default command to specify the default output for the module, and the corresponding import statement does not need to use curly braces. This is more akin to the ADM citation.

/** export default **///definition output export default {basicnum, add};//introduce import math from './math '; function test (ele) {    ele.te Xtcontent = 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.

Front-end modularity scheme: COMMONJS/AMD/CMD/ES6 specification

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.