In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "JavaScript CommonJS, AMD, CMD, ES6 case analysis", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "JavaScript CommonJS, AMD, CMD, ES6 case analysis" bar!
I. Preface
AMD, CMD and CommonJs are modular programming solutions provided in ES5, and import/export is a new modular programming scheme in ES6.
So, what exactly is AMD, CMD, CommonJs? What is the difference between them? Which modular programming specification should be chosen for project development, and how to use it? This post will answer the above questions one by one.
II. Definition of AMD- asynchronous module
AMD is an abbreviation for "Asynchronous Module Definition", that is, "asynchronous module definition". It loads the module asynchronously, and the loading of the module does not affect the operation of the following statements.
In this case, async means that other tasks in the browser (dom build, css rendering, etc.) are not blocked, while the internal loading is synchronous (callback is performed immediately after the module is loaded).
RequireJS: is an AMD framework, can load JS files 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, through the variable to reference the method in the module, and finally through the return to output.
AMD is the standardized output of module definition in the process of promotion by RequireJS. It is a concept, and RequireJS is the implementation of this concept, just as JavaScript language is the implementation of ECMAScript specification. AMD is an organization under which RequireJS is a custom scripting language.
Unlike CommonJS, it requires two parameters:
Require ([module], callback)
The first parameter, [module], is an array in which the members are the modules to be loaded, and callback is the callback function after loading. If you change the above code to AMD mode:
Require (['math'], function (math) {math.add (2,3);})
Where the parameters in the callback function correspond to the members (modules) in the array.
RequireJS loading module, using the AMD specification. That is, the module must be written in the way specified by AMD.
Specifically, module writing must be defined using a specific define () function. If a module does not depend on other modules, it can be written directly in the define () function.
Define (id, dependencies, factory)
Id: the name of the module. If this parameter is not provided, the name of the module should default to the specified script name requested by the module loader
Dependencies: the dependency of the module, the literal amount of the array that has been identified by the module defined by the module. The dependent parameter is optional, and if you omit this parameter, it should default to ["require", "exports", "module"]. However, if the length property of the factory method is less than 3, the loader chooses to call the factory method with the number of parameters specified by the length property of the function.
Factory: the factory function of the module that initializes the function or object to be executed. 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.
Suppose you now have a math.js file that defines a math module. So, math.js is written as follows:
/ / math.jsdefine (function () {var add = function (x, y) {return x + y;} return {add: add}})
The loading method is as follows:
/ / main.jsrequire (['math'], function (math) {alert (math.add (1,1));})
If the math module depends on other modules, write as follows:
/ / math.jsdefine (['dependenceModule'], function (dependenceModule) {/ /...})
When the require () function loads the math module, the dependenceModule module loads first. When there are multiple dependencies, all dependencies are written in the first parameter array of the define () function, so AMD is dependent prefix. This is different from the CMD specification, which relies on proximity.
CMD
III. Definition of CMD- synchronization module
CMD, namely Common Module Definition general module definition, is the standardized output of module definition by SeaJS in the process of promotion, is a synchronous module definition, is a standard of SeaJS, SeaJS is an implementation of CMD concept, and SeaJS is a module development js framework provided by Taobao team Yubo. The CMD specification is developed in China, just as AMD has a requireJS,CMD and a browser implementation SeaJS,SeaJS has to solve the same problems as requireJS, except that the mode of module definition and the timing of module loading (can be said to run, parse) are different.
CMD is defined by define (), does not depend on the front, loads the jQuery plug-in through require, CMD is dependent on the nearest, where the plug-in is used, where the plug-in is require, that is, it is a synchronous concept.
In the CMD specification, a module is a file. The code is written in the following format:
Define (function (require, exports, module) {/ / Module Code})
Among them
Require is a parameter that can be imported into other modules
Exports can export some properties and methods in the module.
Module is an object that stores properties and methods associated with the current module.
AMD is a dependency preposition, so when defining a module, you have to declare the module on which it depends.
CMD is the nearest on-demand loading dependency. You can only go to require when a module is used. The sample code is as follows:
/ / CMDdefine (function (require, exports, module) {var a = require ('. / a') a.doSomething () / / omit 100 lines here var b = require ('. / b') / dependency can be written nearby b.doSomething () / /}) / / AMD default recommendation is define (['. / ajar,'. / b'], function (a) B) {/ / dependency must be written at the beginning of a.doSomething () / / omitting 100 lines of b.doSomething ().}) IV. CommonJS specification
The CommonJS specification is defined through module.exports, does not support module.exports in front-end browsers, and is used through the node.js back-end. The Nodejs side uses the CommonJS specification, and the front-end browsers generally use AMD, CMD, ES6 and other defined modular development specifications.
The ultimate goal of CommonJS is to provide a standard library similar to Python,Ruby and Java. In this way, developers can write applications in CommonJS API, which can then run in different JavaScript interpreters and different host environments.
On CommonJS-compatible systems, you can use JavaScript to develop the following programs:
Server-side JavaScript application
Command line tool
Graphical interface application
Hybrid applications (e.g., Titanium or Adobe AIR)
In 2009, American programmer Ryan Dahl created the node.js project, which uses the javascript language for server-side programming. This marks the official birth of "Javascript modular programming". NodeJS is the implementation of CommonJS specification, and webpack is also written in the form of CommonJS.
The module system of node.js is implemented with reference to the CommonJS specification. In CommonJS, there is a global method, require (), to load the module. Assuming that there is a mathematical module math.js, it can be loaded as follows.
Var math = require ('math')
You can then call the methods provided by the module:
Var math = require ('math'); math.add (2Jing 3); / / 5
The modules defined by CommonJS are divided into: module reference (require), module definition (exports) and module identification (module).
Among them
Require () is used to introduce external modules
The exports object is used to export the method or variable of the current module, the only exit
The module object represents the module itself.
Although NodeJS follows the CommonJS specification, it also makes some trade-offs and adds something new.
NPM, as a Node package manager, also follows the CommonJS specification.
Let's talk about the principle and simple implementation of commonJS:
1. Principle
The root cause of browser incompatibility with CommonJS is the lack of four Node.js environment variables.
Moduleexportsrequireglobal
As long as these four variables are provided, the browser can load the CommonJS module.
Here is a simple example.
Var module = {exports: {}}; (function (module, exports) {exports.multiply = function (n) {return n * 1000};} (module, module.exports)) var f = module.exports.multiply; f (5) / / 5000
The above code provides two external variables module and exports to an immediate execution function, and the module is placed in the immediate execution function. The output value of the module is placed in the module.exports, thus realizing the loading of the module.
2. The realization of Browserify
Browserify is the most commonly used CommonJS format conversion tool at present.
Take a look at an example where the main.js module loads the foo.js module.
/ / foo.jsmodule.exports = function (x) {console.log (x);}; / / main.jsvar foo = require (". / foo"); foo ("Hi")
Using the following command, you can convert main.js to a format that is available to the browser.
$browserify main.js > compiled.js
Among them, what exactly did Browserify do? Install browser-unpack and it will be clear.
$npm install browser-unpack-g
Then, unpack the previously generated compile.js.
$browser-unpack
< compiled.js[ { "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 }] 可以看到,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;}, 1000); module.exports = {foo: foo,}; / / execution: node a.js// execution result: / / 1 hand / 1 hand / 1
The above code shows that after the b module is loaded, its internal foo changes will not affect the output exports.foo. This is because foo is a primitive type of value that is cached. So if you want to get the values in the module dynamically in CommonJS, you need to rely on the function delay execution feature.
/ / 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; / / same as exports.foo = 1 setTimeout (() = > {module.exports.foo = 2;}, 500) / / execution: node a.js// execution result: / / 1max / 2max / 2
So we can sum it up:
The module introduced repeatedly by the CommonJS module will not be executed repeatedly, and the re-acquisition module will directly get the exposed module.exports object.
If you need to get the latest values in the module everywhere, you can also update the values on module.exports every time you update the data.
If the property of the exposed module.exports is an object, then this problem does not exist.
At this point, I believe you have a deeper understanding of "JavaScript CommonJS, AMD, CMD, ES6 case analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 292
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.