js module specifications: AMD, CMD, CommonJS

js module specifications: CommonJS, AMD, CMD, ES6

A modular understanding

1. What is a module

A complex procedure according to a certain specification packaged into several files, and combined

2. Why modular?
  • Reduce complexity
  • Improve decoupling
  • Easy to deploy
3, the advantages of modular
  • Avoid naming conflicts (reducing namespace pollution), reducing global variable pollution
  • Improved reusability
  • The code easier to maintain
  • Separation can be achieved on-demand loading module
  • Reducing the number of http requests to a certain extent

Two, CommonJS

CommonJSIs loaded synchronously, NodeJS on the use of CommonJS, because reading module is a local disk on the server, load quickly, for the server. CommonJSSpecification, each file is a module, has its own independent scope, variables, and methods, are not visible to other modules

//加载模块
var modA= require('modA');
modA.start();

三、AMD (Asynchronous Module Definition)

AMD is loaded asynchronously, requireJs application of this specification, first define all the dependencies, then execute the callback function after the load completion.

1, defineto define the module

define(id?,dependencies?,factory). id is a unique string that identifies the type of module (may be omitted), an array literal Dependencies for a block currently defined is dependent module (default file extensions .js), when there is no Dependencies, the module It is an independent module, not dependent on any module. factory is to be instantiated function, a function of parameters dependent on one-module, the function returns a value required, return value of a function that represents the current contents of the module is exposed.

2. Use requireto call module

requireDefined function is require(dependencies,factory). dependencies literal is an array, called a block, Factory need to pass a callback function for explaining the operation performed after the completion of asynchronous loading module
require function itself is a target, which has a function to configure the config functions require operating parameter, config function takes an object as a parameter. config parameter object has the following attributes:

  • baseUrl
    baseUrl parameter specifies the directory of the local module reference position, i.e. the path which the local module with respect to the directory.
  • paths
    paths parameter specifies the location of each module. This position may be a relative location on the server, or may be an external source. The plurality of positions can be defined for each module, if the first loading position fails, the second loading position, we will see later in specific examples.
  • shim
    Some libraries are not compatible with AMD, then you need to specify the value of the shim property. shim is used to help load the library require.js non-AMD specification.
3, citing the example
// module1.js
// 定义一个没有依赖的模块
define(function() {
  let msg = '123456';
  function get() {
    return msg;
  }
  return { get }; // 暴露模块
})

// module2.js
// 定义一个依赖module1的模块
define(['module1'],function(module1) {
  let _msg_ = '7890';
  function con() {
    return module1.get()+_msg_;// 将两个字符串连接起来
  }
  return { con }; // 暴露模块
})

// main.js
function(){
  require.config({
    baseUrl:'./modules/',
    paths:{
      module1:'module1',
      module2:'module2'
    },
  });
  require([module2],function(module2){
    console.log(module2.con());
  });
}();// 1234567890

// index.html
<!DOCTYPE html>
<html>
  <head>
    <title>AMD</title>
  </head>
  <body>
    <!-- 引入require.js并指定js主文件的入口 -->
    <script data-main="js/main" src="js/libs/require.js"></script>
  </body>
</html>

Third-party libraries in module.js file, main.js file must have the appropriate path configuration. Furthermore, we can also specify a library to a plurality of addresses for alternate address, using the alternate address when the address before the failure, for example

// main.js
function(){
  require.config({
    baseUrl:'./modules/',
    paths:{
      jquery:'xxxx'
    },
  });
}();

require.config({
    paths: {
        jquery: [
        // 路径定义为数组,数组的每一项为一个地址定义
            '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js',
            'lib/jquery'
        ]
    }
});

三、CMD (Common Module Definition)

CommonJS integrated features and specifications of AMD specifically for browser-side, asynchronous loading module, the module specification defined the format of writing and basic rules of interaction.
CMD is defined by specifications define the keyword module, the basic syntax for the define (factory), factory values may be a function or any legal value (objects, arrays, strings, etc.). When the factory is a function representing the constructor of the module, the function has three parameters ---- "require, exports, module" . require parameter is a method that takes as parameters unique identification module, to introduce them. exports parameters for exposing module, module parameter points to the current block.

Asynchronous load module, seajs respected specification, is dependent on the CMD nearby, when used again require

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>CMD Demo</title>
    <!--引入Sea.js库-->
    <script type="text/javascript" src="../../sea-modules/seajs/seajs/2.2.0/sea.js"></script>
    <script type="text/javascript">
      seajs.use("../../static/cmd/main");// 使用模块
    </script>
  </head>
</html>

// module1.js
// factory为对象
define({foo:foo});

// module2.js
// factory为字符串
define(foo:"123456");

// module3.js
// factory为数字
define(foo:666);

The above is factoryfor the general case when the value of one when we look at the following factorytime as a function

// main.js
define(function(require) {
  //通过riquire引用模块
  var module1=require('./module1');
  var module2=require('./module2');
  var module3=require('./module3');
  console.log(module1.foo);// foo
  console.log(module2.foo);// 123456
  console.log(module3.foo);// 666
});

Determine whether the current page there CMD Module Loader

if(tepyof define === "function" && define.cmd){
  // 有Sea.js等CMD模块加载器存在
}

The biggest difference between AMD and CMD is dependent on the timing of the implementation of the different processing modules, rather than loading time or different ways, both are all asynchronous loading module.
AMD relies front, js can easily know who depend module is loaded immediately; and CMD nearby depend, need to use the module into a string parsing again know those dependent module

Four, ES6

ES6 module design specification is to be able to determine module dependencies as much as possible when static, enables the compiler. The CommonJS and CMD, can only determine dependencies at runtime.

  • Expose interfaces
    export command is used to specify the module's external interfaces, the basic syntax for the export xxx, exposed interface can be objects, functions, basic types of variables. Also you can use export default xxx specifies the default output modules, because many users do not know when the attribute name to be loaded module
  • Invoking module
    import command input function provided by the other modules, the basic syntax of import from xxx xxx, xxx wherein the first module is incorporated attribute names, xxx is the second position of the module.
// module1.js
let s='';
function proc(){
  s='123456';
  return s;
}
export {num,inc};// 暴露接口

// main.js
import {s,proc} from './module1';// 引入依赖
console.log(s);// 
console.log(proc);// 123456

In use CommonJS specification, a copy of the output value, that is after the output changes within a module not affect the output. However, the exact opposite is ES6, ES6 specification is a reference output value, i.e. internal changes affect the output module.
ES6 module is a dynamic reference value will not be cached, the module inside its variable bindings in the module.

Published 27 original articles · won praise 21 · views 4614

Guess you like

Origin blog.csdn.net/weixin_43997143/article/details/100356407