JavaScript modular programming specifications CommonJS, AMD, CMD, ES6

WBOY
Release: 2022-03-10 13:53:18
forward
1899 people have browsed it

This article brings you relevant knowledge aboutjavascript, which mainly introduces modular programming specifications, CommonJS, AMD, CMD and ES6 related issues. I hope it will be helpful to everyone.

JavaScript modular programming specifications CommonJS, AMD, CMD, ES6

Related recommendations:javascript learning tutorial

1. Foreword

AMD, CMD and CommonJsare modular programming solutions provided inES5, andimport/exportis a new modular programming solution provided inES6.

So, what exactly isAMD, CMD, CommonJs? What are the differences between them? Which modular programming specification should be used for project development, and how to use it? This blog post will answer the above questions one by one.

2. AMD-Asynchronous Module Definition

AMDis the abbreviation of "Asynchronous Module Definition", that is, "Asynchronous Module Definition". It loads modules asynchronously, and the loading of the module does not affect the execution of subsequent statements.

Asynchronous here refers to not blocking other tasks of the browser (dombuilding,cssrendering, etc.), while loading is internally synchronous (immediately after loading the module execution callback).

RequireJS: It is aAMDframework that can loadJSfiles asynchronously, according to the module loading method, through the define() function Definition, the first parameter is an array, which defines some dependent packages, the second parameter is a callback function, which refers to the methods in the module through variables, and finally outputs through return.

AMDis the standardized output of module definition inRequireJSduring the promotion process. It is a concept,RequireJSis the The implementation of this concept is just like theJavaScriptlanguage is the implementation of theECMAScriptspecification.AMDis an organization,RequireJSis a set of scripting languages customized under this organization.

Different fromCommonJS, it requires two parameters:

require([module], callback);
Copy after login

The first parameter[module]is an array with the members is the module to be loaded,callbackis the callback function after loading is completed. If the above code is changed to theAMDmethod:

require(['math'], function(math) { math.add(2, 3);})
Copy after login

Among them, the parameters in the callback function correspond to the members (modules) in the array.

requireJSLoading module adopts theAMDspecification. In other words, the module must be written in the manner specified byAMD.

Specifically, module writing must be defined using a specificdefine()function. If a module does not depend on other modules, it can be written directly in thedefine()function.

define(id, dependencies, factory);
Copy after login
  • id: The name of the module. If this parameter is not provided, the module name should default to the specified script name requested by the module loader;
  • dependencies: Module dependencies, array literals of module identifiers that have been defined by the module. The dependency parameter is optional, if this parameter is omitted it should default to["require", "exports", "module"]. However, if the factory method's length attribute is less than 3, the loader will choose to call the factory method with the number of arguments specified by the function's length attribute.
  • factory: Factory function of the module, the function or object to be executed during module initialization. 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.

Assume that there is now amath.jsfile that defines amathmodule. Then,math.jsis written as follows:

// math.jsdefine(function() { var add = function(x, y) { return x + y; } return { add: add }})
Copy after login

The loading method is as follows:

// main.jsrequire(['math'], function(math) { alert(math.add(1, 1));})
Copy after login

If themathmodule also depends on other modules, it is written as follows:

// math.jsdefine(['dependenceModule'], function(dependenceModule) { // ...})
Copy after login

When therequire()function loads themathmodule, thedependenceModulemodule will be loaded first. When there are multiple dependencies, all dependencies are written in the first parameter array of thedefine()function, soAMDis pre-dependent. This is different from theCMDspecification, which relies on proximity.
CMD

3. CMD-synchronization module definition

CMDisCommon Module Definitioncommon module definition, which isSeaJSThe standardized output of module definition during the promotion process is a synchronized module definition, which is a standard ofSeaJS,SeaJSis a concept ofCMDImplementation,SeaJSis a module developmentjsframework provided by Taobao team Yubo.CMDThe specification is developed domestically, just likeAMDhasrequireJS,CMDhas a browser implementationSeaJS,SeaJSThe problem to be solved is the same asrequireJS, but it is different in the module definition method and module loading (it can be said to run, parse) timing.

CMD通过define()定义,没有依赖前置,通过require加载jQuery插件,CMD是依赖就近,在什么地方使用到插件就在什么地方require该插件,即用即返,这是一个同步的概念。

CMD规范中,一个模块就是一个文件。代码的书写格式如下:

define(function(require, exports, module) { // 模块代码});
Copy after login

其中,

  • require是可以把其他模块导入进来的一个参数;
  • exports是可以把模块内的一些属性和方法导出的;
  • module是一个对象,上面存储了与当前模块相关联的一些属性和方法。

AMD是依赖关系前置,在定义模块的时候就要声明其依赖的模块;
CMD是按需加载依赖就近,只有在用到某个模块的时候再去require,示例代码如下:

// CMDdefine(function(require, exports, module) { var a = require('./a') a.doSomething() // 此处略去 100 行 var b = require('./b') // 依赖可以就近书写 b.doSomething() // ... })// AMD 默认推荐的是define(['./a', './b'], function(a, b) { // 依赖必须一开始就写好 a.doSomething() // 此处略去 100 行 b.doSomething() ...})
Copy after login

四、CommonJS 规范

CommonJS规范是通过module.exports定义的,在前端浏览器里面并不支持module.exports,通过node.js后端使用。Nodejs端使用CommonJS规范,前端浏览器一般使用AMDCMDES6等定义模块化开发规范。

CommonJS的终极目标是提供一个类似PythonRubyJava的标准库。这样的话,开发者可以使用CommonJS API编写应用程序,然后这些应用就可以运行在不同的JavaScript解释器和不同的主机环境中。

在兼容CommonJS的系统中,你可以使用JavaScript开发以下程序:

  1. 服务器端JavaScript应用程序;
  2. 命令行工具;
  3. 图形界面应用程序;
  4. 混合应用程序(如,Titanium或Adobe AIR);

2009年,美国程序员Ryan Dahl创造了node.js项目,将javascript语言用于服务器端编程。这标志"Javascript模块化编程"正式诞生。NodeJSCommonJS规范的实现,webpack也是以CommonJS的形式来书写。

node.js的模块系统,就是参照CommonJS规范实现的。在CommonJS中,有一个全局性方法require(),用于加载模块。假定有一个数学模块math.js,就可以像下面这样加载。

var math = require('math');
Copy after login

然后,就可以调用模块提供的方法:

var math = require('math');math.add(2,3); // 5
Copy after login

CommonJS定义的模块分为:模块引用(require)模块定义(exports)模块标识(module)
其中,

  • require()用来引入外部模块;
  • exports对象用于导出当前模块的方法或变量,唯一的导出口;
  • module对象就代表模块本身。

虽说NodeJS遵循CommonJS的规范,但是相比也是做了一些取舍,添了一些新东西的。

NPM作为Node包管理器,同样遵循CommonJS规范。

下面讲讲commonJS的原理以及简易实现:

1、原理
浏览器不兼容CommonJS的根本原因,在于缺少四个Node.js环境变量。

module exports require global
Copy after login

只要能够提供这四个变量,浏览器就能加载CommonJS模块。

下面是一个简单的示例。

var module = { exports: {}};(function(module, exports) { exports.multiply = function (n) { return n * 1000 }; }(module, module.exports))var f = module.exports.multiply; f(5) // 5000
Copy after login

上面代码向一个立即执行函数提供 module 和 exports 两个外部变量,模块就放在这个立即执行函数里面。模块的输出值放在 module.exports 之中,这样就实现了模块的加载。

2、Browserify 的实现
Browserify是目前最常用的CommonJS格式转换工具。

请看一个例子,main.js模块加载foo.js模块。

// foo.jsmodule.exports = function(x) { console.log(x);};// main.jsvar foo = require("./foo");foo("Hi");
Copy after login

使用下面的命令,就能将main.js转为浏览器可用的格式。

$ browserify main.js > compiled.js
Copy after login

其中,Browserify到底做了什么?安装一下browser-unpack,就清楚了。

$ npm install browser-unpack -g
Copy after login

然后,将前面生成的compile.js解包。

$ browser-unpack < compiled.js
Copy after login
[ { "id":1, "source":"module.exports = function(x) {\n console.log(x);\n};", "deps":{} }, { "id":2, "source":"var foo = require(\"./foo\");\nfoo(\"Hi\");", "deps":{"./foo":1}, "entry":true }]
Copy after login

可以看到,browerify将所有模块放入一个数组,id属性是模块的编号,source属性是模块的源码,deps属性是模块的依赖。

因为main.js里面加载了foo.js,所以deps属性就指定./foo对应1号模块。执行的时候,浏览器遇到require('./foo')语句,就自动执行1号模块的source属性,并将执行后的module.exports属性值输出。

五、ES6

有关es6模块特性,强烈推荐阮一峰老师的:ECMAScript 6 入门 - Module 的语法专栏。

要说ES6模块特性,那么就先说说ES6模块跟CommonJS模块的不同之处。

  • ES6模块输出的是值的引用,输出接口动态绑定,而CommonJS输出的是值的拷贝;
  • ES6模块编译时执行,而CommonJS模块总是在运行时加载。

CommonJS模块输出的是值的拷贝(原始值的拷贝),也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。

// a.jsvar b = require('./b');console.log(b.foo);setTimeout(() => { console.log(b.foo); console.log(require('./b').foo);}, 1000);// b.jslet foo = 1;setTimeout(() => { foo = 2;}, 500);module.exports = { foo: foo,};// 执行:node a.js// 执行结果:// 1// 1// 1
Copy after login

上面代码说明,b 模块加载以后,它的内部 foo 变化就影响不到输出的 exports.foo 了。这是因为 foo 是一个原始类型的值,会被缓存。所以如果你想要在CommonJS中动态获取模块中的值,那么就需要借助于函数延时执行的特性。

// a.jsvar b = require('./b');console.log(b.foo);setTimeout(() => { console.log(b.foo); console.log(require('./b').foo);}, 1000);// b.jsmodule.exports.foo = 1; // 同 exports.foo = 1 setTimeout(() => { module.exports.foo = 2;}, 500);// 执行:node a.js// 执行结果:// 1// 2// 2
Copy after login

所以我们可以总结一下:

  • CommonJS模块重复引入的模块并不会重复执行,再次获取模块直接获得暴露的module.exports对象。
  • 如果你需要处处获取到模块内的最新值的话,也可以每次更新数据的时候每次都要去更新module.exports上的值
  • 如果暴露的module.exports的属性是个对象,那就不存在这个问题了。

相关推荐:javascript视频教程

The above is the detailed content of JavaScript modular programming specifications CommonJS, AMD, CMD, ES6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!