Home  >  Article  >  Web Front-end  >  Detailed explanation of module specifications in JS (CommonJS, AMD, CMD)

Detailed explanation of module specifications in JS (CommonJS, AMD, CMD)

php是最好的语言
php是最好的语言Original
2018-08-07 09:21:442009browse

Answer me first: Why are modules important?

Answer: Because of the modules, we can use other people's code more conveniently, and load whatever modules we want for whatever functions we want.
However, there is a premise for this, that is, everyone must write the module in the same way, otherwise you have your way of writing, and I have my way of writing, wouldn't it be a mess!

#So the following three module specifications came out, and this article came out (spelled out {covering face and laughing}).

Module specifications in JS (CommonJS, AMD, CMD), if you have heard of js modularization, then you should have heard of CommonJS or AMD or even I have heard of these CMD specifications, but before that I really just listened to them. Now let’s take a look at what these specifications are and what they do. This article includes the sources of these three specifications and the principles of their corresponding products.

1. CommonJS

1. At the beginning, everyone thought JS was a hot chick , it’s useless. The officially defined API can only build browser-based applications. You’re kidding me, this is too narrow (a high-end word is used, quack). CommonJS can’t stand it anymore. CommonJS API defines many common APIs used by applications (mainly non-browser applications) fill this gap. Its ultimate goal is to provide a standard library similar to Python, Ruby and Java. In this case, developers can use the CommonJS API to write applications, and then these applications can run in different JavaScript interpreters and different host environments.

In systems compatible with CommonJS, you can use JavaScript to develop the following programs:

(1). Server-side JavaScript application

(2). Command line tools
(3). Graphical interface applications
(4).Hybrid applications (e.g., Titanium or Adobe AIR)

In 2009, American programmer Ryan Dahl created the node.js project to use the JavaScript language for server-side programming. This marks the official birth of "Javascript modular programming". Because to be honest, in a browser environment, not having modules is not a big problem. After all, the complexity of web programs is limited; but on the server side, there must be modules to interact with the operating system and other applications, otherwise there is no way. programming. NodeJS is an implementation of the 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(), which is used to load modules. Assuming there is a math module math.js, it can be loaded as follows.

var math = require('math');

Then, you can call the method provided by the module:

var math = require('math');

math.add(2,3); // 5

The modules defined by CommonJS are divided into: {module reference (require)} {module definition (exports)} {module identification (module)}

require() is used to introduce external modules; the exports object is used to export the methods or variables of the current module, the only export port; the module object represents the module itself.

Although Node follows the specifications of CommonJS, it has made some trade-offs and added some new things.

However, after talking about CommonJS and also talking about Node, I think we need to understand NPM first. As the package manager of Node, NPM is not to help Node solve the installation problem of dependent packages. Then it must also follow the CommonJS specification. It follows the package specification (or theory). CommonJS WIKI talks about its history, and also introduces modules, packages, etc.

Let’s talk about the principle and simple implementation of commonJS:

1. Principle

Browse The fundamental reason why the server is not compatible with CommonJS is the lack of four Node.js environment variables.

  • module

  • ##exports

  • require

  • global

As long as these four variables can be provided, the browser can load the CommonJS module.

The following is a simple example.

<code class="language-javascript"><span style="font-family:'Microsoft YaHei';font-size:16px;"><code class="language-javascript"><br><span class="token keyword">var module <span class="token operator">= <span class="token punctuation">{<br> exports<span class="token punctuation">: <span class="token punctuation">{<span class="token punctuation">}<br><span class="token punctuation">}<span class="token punctuation">;<br><br><span class="token punctuation">(<span class="token keyword">function<span class="token punctuation">(module<span class="token punctuation">, exports<span class="token punctuation">) <span class="token punctuation">{<br> exports<span class="token punctuation">.multiply <span class="token operator">= <span class="token keyword">function <span class="token punctuation">(n<span class="token punctuation">) <span class="token punctuation">{ <span class="token keyword">return n <span class="token operator">* <span class="token number">1000 <span class="token punctuation">}<span class="token punctuation">;<br><span class="token punctuation">}<span class="token punctuation">(module<span class="token punctuation">, module<span class="token punctuation">.exports<span class="token punctuation">)<span class="token punctuation">)<br><br><span class="token keyword">var f <span class="token operator">= module<span class="token punctuation">.exports<span class="token punctuation">.multiply<span class="token punctuation">;<br><span class="token function">f<span class="token punctuation">(<span class="token number">5<span class="token punctuation">)<span class="token comment"> // 5000 <br></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span></code>

The above code provides two external variables, module and exports, to an immediate execution function. The module is placed in this immediate execution function. . The output value of the module is placed in module.exports, thus realizing the loading of the module.

2. Implementation of Browserify

If you know the principle, you can make tools . Browserify is currently the most commonly used CommonJS format conversion tool.

Please look at an example where the main.js module loads the foo.js module.

<code class="language-javascript"><span style="font-family:'Microsoft YaHei';font-size:16px;"><code class="language-javascript"><span class="token comment"><br>// foo.js<br>module<span class="token punctuation">.exports <span class="token operator">= <span class="token keyword">function<span class="token punctuation">(x<span class="token punctuation">) <span class="token punctuation">{<br> console<span class="token punctuation">.<span class="token function">log<span class="token punctuation">(x<span class="token punctuation">)<span class="token punctuation">;<br><span class="token punctuation">}<span class="token punctuation">;<br><span class="token comment"><br>// main.js<br><span class="token keyword">var foo <span class="token operator">= <span class="token function">require<span class="token punctuation">(<span class="token string">"./foo"<span class="token punctuation">)<span class="token punctuation">;<br><span class="token function">foo<span class="token punctuation">(<span class="token string">"Hi"<span class="token punctuation">)<span class="token punctuation">;<br></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span></code>

Use the following command to convert main.js into a format usable by the browser.

<span style="font-family:&#39;Microsoft YaHei&#39;;font-size:16px;"><code class="language-bash"><br/>$ browserify main<span class="token punctuation">.js <span class="token operator">> compiled<span class="token punctuation">.js<br/></span></span></span></code></span>

What exactly does Browserify do? Install browser-unpack and you can see clearly.

<span style="font-family:&#39;Microsoft YaHei&#39;;font-size:16px;"><code class="language-bash"><br/>$ npm install browser<span class="token operator">-unpack <span class="token operator">-g<br/></span></span></code></span>

Then, unpack the compile.js generated previously.

<span style="font-family:&#39;Microsoft YaHei&#39;;font-size:16px;"><code class="language-bash"><br/>$ browser<span class="token operator">-unpack <span class="token operator">< compiled<span class="token punctuation">.js<br/><br/><span class="token punctuation">[<br/><span class="token punctuation">{<br/><span class="token string">"id"<span class="token punctuation">:<span class="token number">1<span class="token punctuation">,<br/><span class="token string">"source"<span class="token punctuation">:<span class="token string">"module.exports = function(x) {\n console.log(x);\n};"<span class="token punctuation">,<br/><span class="token string">"deps"<span class="token punctuation">:<span class="token punctuation">{<span class="token punctuation">}<br/><span class="token punctuation">}<span class="token punctuation">,<br/><span class="token punctuation">{<br/><span class="token string">"id"<span class="token punctuation">:<span class="token number">2<span class="token punctuation">,<br/><span class="token string">"source"<span class="token punctuation">:<span class="token string">"var foo = require(\"./foo\");\nfoo(\"Hi\");"<span class="token punctuation">,<br/><span class="token string">"deps"<span class="token punctuation">:<span class="token punctuation">{<span class="token string">"./foo"<span class="token punctuation">:<span class="token number">1<span class="token punctuation">}<span class="token punctuation">,<br/><span class="token string">"entry"<span class="token punctuation">:<span class="token boolean">true<br/><span class="token punctuation">}<br/><span class="token punctuation">]<br/></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span>

As you can see, browerify puts all modules into an array, the id attribute is the number of the module, and the source attribute is the module's Source code, deps attribute is the dependency of the module.

Because foo.js is loaded in main.js, the deps attribute specifies that ./foo corresponds to module No. 1. During execution, when the browser encounters the require('./foo') statement, it automatically executes the source attribute of module 1 and outputs the module.exports attribute value after execution.

3. Tiny Browser Require

Although Browserify is very powerful, it cannot be operated in the browser, which is sometimes very inconvenient.

I made a pure browser CommonJS module loader tiny-browser-require based on the internal implementation of mocha. There is no need for a command line at all, just put it directly into the browser. The entire code is only more than 30 lines.

Its logic is very simple, that is, reading the module into an array, and the loading path is the module's id.

<code class="language-javascript"><span style="font-family:'Microsoft YaHei';font-size:16px;"><code class="language-javascript"><br><span class="token keyword">function <span class="token function">require<span class="token punctuation">(p<span class="token punctuation">)<span class="token punctuation">{<br><span class="token keyword">var path <span class="token operator">= require<span class="token punctuation">.<span class="token function">resolve<span class="token punctuation">(p<span class="token punctuation">)<span class="token punctuation">;<br><span class="token keyword">var mod <span class="token operator">= require<span class="token punctuation">.modules<span class="token punctuation">[path<span class="token punctuation">]<span class="token punctuation">;<br><span class="token keyword">if <span class="token punctuation">(<span class="token operator">!mod<span class="token punctuation">) <span class="token keyword">throw <span class="token keyword">new <span class="token class-name">Error<span class="token punctuation">(<span class="token string">'failed to require "' <span class="token operator">+ p <span class="token operator">+ <span class="token string">'"'<span class="token punctuation">)<span class="token punctuation">;<br><span class="token keyword">if <span class="token punctuation">(<span class="token operator">!mod<span class="token punctuation">.exports<span class="token punctuation">) <span class="token punctuation">{<br> mod<span class="token punctuation">.exports <span class="token operator">= <span class="token punctuation">{<span class="token punctuation">}<span class="token punctuation">;<br> mod<span class="token punctuation">.<span class="token function">call<span class="token punctuation">(mod<span class="token punctuation">.exports<span class="token punctuation">, mod<span class="token punctuation">, mod<span class="token punctuation">.exports<span class="token punctuation">, require<span class="token punctuation">.<span class="token function">relative<span class="token punctuation">(path<span class="token punctuation">)<span class="token punctuation">)<span class="token punctuation">;<br><span class="token punctuation">}<br><span class="token keyword">return mod<span class="token punctuation">.exports<span class="token punctuation">;<br><span class="token punctuation">}<br><br>require<span class="token punctuation">.modules <span class="token operator">= <span class="token punctuation">{<span class="token punctuation">}<span class="token punctuation">;<br><br>require<span class="token punctuation">.resolve <span class="token operator">= <span class="token keyword">function <span class="token punctuation">(path<span class="token punctuation">)<span class="token punctuation">{<br><span class="token keyword">var orig <span class="token operator">= path<span class="token punctuation">;<br><span class="token keyword">var reg <span class="token operator">= path <span class="token operator">+ <span class="token string">'.js'<span class="token punctuation">;<br><span class="token keyword">var index <span class="token operator">= path <span class="token operator">+ <span class="token string">'/index.js'<span class="token punctuation">;<br><span class="token keyword">return require<span class="token punctuation">.modules<span class="token punctuation">[reg<span class="token punctuation">] <span class="token operator">&& reg<br><span class="token operator">|| require<span class="token punctuation">.modules<span class="token punctuation">[index<span class="token punctuation">] <span class="token operator">&& index<br><span class="token operator">|| orig<span class="token punctuation">;<br><span class="token punctuation">}<span class="token punctuation">;<br><br>require<span class="token punctuation">.register <span class="token operator">= <span class="token keyword">function <span class="token punctuation">(path<span class="token punctuation">, fn<span class="token punctuation">)<span class="token punctuation">{<br> require<span class="token punctuation">.modules<span class="token punctuation">[path<span class="token punctuation">] <span class="token operator">= fn<span class="token punctuation">;<br><span class="token punctuation">}<span class="token punctuation">;<br><br>require<span class="token punctuation">.relative <span class="token operator">= <span class="token keyword">function <span class="token punctuation">(parent<span class="token punctuation">) <span class="token punctuation">{<br><span class="token keyword">return <span class="token keyword">function<span class="token punctuation">(p<span class="token punctuation">)<span class="token punctuation">{<br><span class="token keyword">if <span class="token punctuation">(<span class="token string">'.' <span class="token operator">!<span class="token operator">= p<span class="token punctuation">.<span class="token function">charAt<span class="token punctuation">(<span class="token number">0<span class="token punctuation">)<span class="token punctuation">) <span class="token keyword">return <span class="token function">require<span class="token punctuation">(p<span class="token punctuation">)<span class="token punctuation">;<br><span class="token keyword">var path <span class="token operator">= parent<span class="token punctuation">.<span class="token function">split<span class="token punctuation">(<span class="token string">'/'<span class="token punctuation">)<span class="token punctuation">;<br><span class="token keyword">var segs <span class="token operator">= p<span class="token punctuation">.<span class="token function">split<span class="token punctuation">(<span class="token string">'/'<span class="token punctuation">)<span class="token punctuation">;<br> path<span class="token punctuation">.<span class="token function">pop<span class="token punctuation">(<span class="token punctuation">)<span class="token punctuation">;<br><br><span class="token keyword">for <span class="token punctuation">(<span class="token keyword">var i <span class="token operator">= <span class="token number">0<span class="token punctuation">; i <span class="token operator">945e8d4292ce0af7e515c6c2ee692956<br><br>3f1c4e4b6b16bbbd69b2ee476dc4f83a<br>require.register("moduleId", function(module, exports, require){<br> // Module code goes here<br>});<br>var result = require("moduleId");<br>2cacc6d41bbb37262a98f745aa00fbf0<br></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span></code>

 还是以前面的 main.js 加载 foo.js 为例。

<code class="language-javascript"><span style="font-family:'Microsoft YaHei';font-size:16px;"><code class="language-javascript"><br>require<span class="token punctuation">.<span class="token function">register<span class="token punctuation">(<span class="token string">"./foo.js"<span class="token punctuation">, <span class="token keyword">function<span class="token punctuation">(module<span class="token punctuation">, exports<span class="token punctuation">, require<span class="token punctuation">)<span class="token punctuation">{<br> module<span class="token punctuation">.exports <span class="token operator">= <span class="token keyword">function<span class="token punctuation">(x<span class="token punctuation">) <span class="token punctuation">{<br> console<span class="token punctuation">.<span class="token function">log<span class="token punctuation">(x<span class="token punctuation">)<span class="token punctuation">;<br><span class="token punctuation">}<span class="token punctuation">;<br><span class="token punctuation">}<span class="token punctuation">)<span class="token punctuation">;<br><br><span class="token keyword">var foo <span class="token operator">= <span class="token function">require<span class="token punctuation">(<span class="token string">"./foo.js"<span class="token punctuation">)<span class="token punctuation">;<br><span class="token function">foo<span class="token punctuation">(<span class="token string">"Hi"<span class="token punctuation">)<span class="token punctuation">;<br></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span></code>

 注意,这个库只模拟了 require 、module 、exports 三个变量,如果模块还用到了 global 或者其他 Node 专有变量(比如 process),就通过立即执行函数提供即可。

二、AMD

基于commonJS规范的nodeJS出来以后,服务端的模块概念已经形成很自然地,大家就想要客户端模块。而且最好两者能够兼容,一个模块不用修改,在服务器和浏览器都可以运行。但是,由于一个重大的局限,使得CommonJS规范不适用于浏览器环境。还是上面的代码,如果在浏览器中运行,会有一个很大的问题,你能看出来吗?

  var math = require('math');

  math.add(2, 3);

 第二行math.add(2, 3),在第一行require('math')之后运行,因此必须等math.js加载完成。也就是说,如果加载时间很长,整个应用就会停在那里等。您会注意到 require 是同步的。

这对服务器端不是一个问题,因为所有的模块都存放在本地硬盘,可以同步加载完成,等待时间就是硬盘的读取时间。但是,对于浏览器,这却是一个大问题,因为模块都放在服务器端,等待时间取决于网速的快慢,可能要等很长时间,浏览器处于"假死"状态。

 因此,浏览器端的模块,不能采用"同步加载"(synchronous),只能采用"异步加载"(asynchronous)。这就是AMD规范诞生的背景。

CommonJS是主要为了JS在后端的表现制定的,他是不适合前端的,AMD(异步模块定义)出现了,它就主要为前端JS的表现制定规范。

AMD是"Asynchronous Module Definition"的缩写,意思就是"异步模块定义"。它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。

AMD也采用require()语句加载模块,但是不同于CommonJS,它要求两个参数:

  require([module], callback);

第一个参数[module],是一个数组,里面的成员就是要加载的模块;第二个参数callback,则是加载成功之后的回调函数。如果将前面的代码改写成AMD形式,就是下面这样:

  require(['math'], function (math) {

    math.add(2, 3);

  });

math.add() and math module loading are not synchronized, and the browser will not freeze. So obviously, AMD is more suitable for the browser environment. Currently, there are two main Javascript libraries that implement the AMD specification: require.js and curl.js.

#RequireJS implements the AMD specification.

Detailed summary: The following uses RequireJS as an example to illustrate the AMD specification

1. Why use require .js?

In the earliest days, all Javascript codes were written in one file, and it was enough to load this one file. Later, there were more and more codes, and one file was no longer enough. It had to be divided into multiple files and loaded in sequence. I believe many people have seen the following web page code

## 82aa3526d91a1e63399c31e3e88e82b62cacc6d41bbb37262a98f745aa00fbf0
 971749f558e9aa1fbc82591b103db9852cacc6d41bbb37262a98f745aa00fbf0
 847a2b365bb3326fcac7e8b83c77b8e107a3fefab51fd2d2ef02a4e62cbe2dba2cacc6d41bbb37262a98f745aa00fbf0
 a5b5ffe2660156a5fc46b07e767cb8819429d6e1efad07153846e528605c447e
 6b211ef2cac820d88c79506423962afa2cacc6d41bbb37262a98f745aa00fbf0

This code loads multiple js files in sequence.

This way of writing has great shortcomings. First of all, when loading, the browser will stop rendering the web page. The more files are loaded, the longer the web page will lose response. Secondly, due to the dependencies between js files, the loading order must be strictly guaranteed (such as the above example) 1.js should be in front of 2.js), and the module with the greatest dependency must be loaded last. When the dependencies are complex, code writing and maintenance will become difficult.

require.js was born to solve these two problems:

## 

 

(1) Implement asynchronous loading of js files to avoid web pages losing response;

 (2) Management between modules Dependencies facilitate code writing and maintenance.

## 2. Loading require.js

Use require.js The first step is to go to the official website to download the latest version.

After downloading, if you put it under the js subdirectory, it can be loaded. ## 7c439788e166f531c8ad0b30265c71032cacc6d41bbb37262a98f745aa00fbf0

##Some people may think that loading this file may also cause the web page to lose response. There are two solutions. One is to load it at the bottom of the web page, and the other is to write it as follows:

## 3132ecf4360d66561b686098990036bf2cacc6d41bbb37262a98f745aa00fbf0

The async attribute indicates that this file needs to be loaded asynchronously to avoid the web page becoming unresponsive. IE does not support this attribute and only supports defer, so defer is also written.

After loading require.js, the next step is to load our own code. Assume that our own code file is main.js and is also placed under the js directory. Then, just write it as follows:

## 35be17e58c59207c30045b58673f385a9429d6e1efad07153846e528605c447e

data-main attribute is used to specify the main module of the web page program. In the above example, it is main.js under the js directory. This file will be loaded by require.js first. Since the default file extension of require.js is js, main.js can be abbreviated to main.

3. How to write the main module

main.js in the previous section, I call it the "main module", which means the entry code for the entire web page. It is a bit like the main() function in C language, all code starts running from here.

Let’s see how to write main.js.

If our code does not depend on any other modules, we can write javascript code directly.

## // main.js

alert("Loading successful!");

But in this case, there is no need to use require.js. A really common situation is that the main module depends on other modules, in which case the require() function defined by the AMD specification must be used.

// main.js

require(['moduleA', 'moduleB', ' moduleC'], function (moduleA, moduleB, moduleC){

    // some code here

##  });

require() function accepts two parameters. The first parameter is an array, indicating the modules it depends on. The above example is ['moduleA', 'moduleB', 'moduleC'], that is, the main module depends on these three modules; the second parameter is a callback function. Currently It will be called after all the modules specified above are loaded successfully. Loaded modules will be passed into this function as parameters, so these modules can be used inside the callback function.

require() loads moduleA, moduleB and moduleC asynchronously, and the browser will not lose response; the callback function it specifies will only be used after the previous modules are loaded successfully. , will run, solving the dependency problem.

Now, let’s look at a practical example.

Assuming that the main module depends on the three modules of jquery, underscore and backbone, main.js can be written like this:

require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone){

   // some code here

 });

require.js will load jQuery, underscore and backbone first, and then run the callback function. The code of the main module is written in the callback function.

4. Module loading

In the last example of the previous section, the main The module's dependent modules are ['jquery', 'underscore', 'backbone']. By default, require.js assumes that these three modules are in the same directory as main.js, with the file names being jquery.js, underscore.js and backbone.js, and then loads them automatically.

Using the require.config() method, we can customize the loading behavior of the module. require.config() is written at the head of the main module (main.js). The parameter is an object, and the paths attribute of this object specifies the loading path of each module.

require.config({

Paths: {

"jquery" : "jquery.min",
"underscore": "underscore.min",
"backbone": "backbone.min"

  }

 });

The above code gives three The file name of a module. The path defaults to the same directory as main.js (js subdirectory). If these modules are in other directories, such as the js/lib directory, there are two ways to write them. One is to specify the paths one by one.

require.config({

Paths: {

"jquery": "lib/jquery.min",

"underscore": "lib/underscore.min",
"backbone": " lib/backbone.min"
##  }

##  });

The other is to directly change the base directory (baseUrl).

require.config({

baseUrl: "js/lib",

Paths: {

"jquery": "jquery.min",

"underscore": "underscore.min ",
   "backbone": "backbone.min"
   }

##  });

If a module is on another host, you can also specify its URL directly, such as:

require.config({

##  Paths: {

   "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"

  }

 });

require.js requires that each module is a separate js file. In this case, if multiple modules are loaded, multiple HTTP requests will be issued, which will affect the loading speed of the web page. Therefore, require.js provides an optimization tool. After the module is deployed, you can use this tool to merge multiple modules into one file to reduce the number of HTTP requests.

5. How to write AMD module

require.js loaded module, using AMD specifications. In other words, the module must be written according to AMD's regulations.

# Specifically, the module must be defined using a specific define() function. If a module does not depend on other modules, it can be defined directly in the define() function.

Assume that there is a math.js file, which defines a math module. Then, math.js should be written like this:

## // math.js

define(function (){

 var add = function (x,y){

##     return x y;

  };

return {

add: add

};

 });

The loading method is as follows:

 // main.js

require(['math'], function (math){

  alert(math.add(1,1));

 });

If this module also depends on other modules, then the first part of the define() function Parameter, must be an array indicating the module's dependencies.

define(['myLib'], function(myLib){

function foo(){

MyLib.doSomething();

##   foo : foo

##  };

 });

When the require() function loads the above module, the myLib.js file will be loaded first.

6. Loading non-standard modules

Theoretically, the module loaded by require.js must be a module defined with the define() function in accordance with AMD specifications. But in fact, although some popular function libraries (such as jQuery) already comply with the AMD specification, many more libraries do not. So, can require.js load non-standard modules?

The answer is yes.

Before loading such modules with require(), you must first use the require.config() method to define some of their characteristics.

For example, the two libraries underscore and backbone are not written using AMD specifications. If you want to load them, you must first define their characteristics.

##Required.config({

shim: {

'underscore' :{
Exports: '_'
},

'backbone': {
   deps: ['underscore', 'jquery'],
   exports: 'Backbone'
   }

  }

 });

##require.config() accepts a configuration object. This object In addition to the paths attribute mentioned earlier, there is also a shim attribute, which is specially used to configure incompatible modules. Specifically, each module must define (1) the exports value (output variable name), which indicates the name of the module when it is called externally; (2) the deps array, which indicates the dependencies of the module.

For example, the jQuery plug-in can be defined like this:

shim: {

 'jquery.scroll': {

   deps: ['jquery'],

   exports: 'jQuery .fn.scroll'

  }

##  }

7. require.js plug-in

require.js also provides a series of plug-ins to implement some specific functions.

domready plug-in allows the callback function to run after the page DOM structure is loaded.

require(['domready!'], function (doc){

   // called once the DOM is ready

 });

text and image plug-ins allow require.js to load text and images document.

define([

    'text!review.txt',

    'image!cat.jpg'

    ],

    function(review,cat){

      console.log(review);

      document.body.appendChild(cat);

    }

  );

 类似的插件还有json和mdown,用于加载json文件和markdown文件。(完)

 另一个人的概括(有点简单):

AMD就只有一个接口:define(id?,dependencies?,factory);

 它要在声明模块的时候制定所有的依赖(dep),并且还要当做形参传到factory中,像这样:

1 define([&#39;dep1&#39;,&#39;dep2&#39;],function(dep1,dep2){...});

 要是没什么依赖,就定义简单的模块,下面这样就可以啦:

<span style="font-family:&#39;幼圆&#39;;font-size:16px;">1 define(function(){<br/>2     var exports = {};<br/>3     exports.method = function(){...};<br/>4     return exports;<br/>5 });</span>

 咦,这里有define,把东西包装起来啦,那Node实现中怎么没看到有define关键字呢,它也要把东西包装起来呀,其实吧,只是Node隐式包装了而已.....

这有AMD的WIKI中文版,讲了很多蛮详细的东西,用到的时候可以查看:AMD的WIKI中文版

三、CMD

大名远扬的玉伯写了seajs,就是遵循他提出的CMD规范,与AMD蛮相近的,不过用起来感觉更加方便些,最重要的是中文版,应有尽有:seajs官方doc

1 define(function(require,exports,module){...});

用过seajs吧,这个不陌生吧,对吧。

前面说AMD,说RequireJS实现了AMD,CMD看起来与AMD好像呀,那RequireJS与SeaJS像不像呢?

虽然CMD与AMD蛮像的,但区别还是挺明显的,官方非官方都有阐述和理解,我觉得吧,说的都挺好:

官方阐述SeaJS与RequireJS异同

SeaJS与RequireJS的最大异同(这个说的也挺好)

相关推荐:

理解前端模块化(CommonJs,AMD和CMD)

JavaScript模块规范之AMD规范和CMD规范

The above is the detailed content of Detailed explanation of module specifications in JS (CommonJS, AMD, CMD). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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