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)
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');The modules defined by CommonJS are divided into: {module reference (require)} {module definition (exports)} {module identification (module)}math.add(2,3); // 5
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: 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. 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. Use the following command to convert main.js into a format usable by the browser. What exactly does Browserify do? Install browser-unpack and you can see clearly. Then, unpack the compile.js generated previously. 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. 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. 使用的时候,先将上面的代码放入页面。然后,将模块放在如下的立即执行函数里面,就可以调用了。 还是以前面的 main.js 加载 foo.js 为例。 注意,这个库只模拟了 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加载完成。也就是说,如果加载时间很长,整个应用就会停在那里等。您会注意到 这对服务器端不是一个问题,因为所有的模块都存放在本地硬盘,可以同步加载完成,等待时间就是硬盘的读取时间。但是,对于浏览器,这却是一个大问题,因为模块都放在服务器端,等待时间取决于网速的快慢,可能要等很长时间,浏览器处于"假死"状态。 因此,浏览器端的模块,不能采用"同步加载"(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 ## 1. Principle
<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>
<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>
<span style="font-family:'Microsoft YaHei';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>
<span style="font-family:'Microsoft YaHei';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>
<span style="font-family:'Microsoft YaHei';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>
3. Tiny Browser Require
<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">< segs<span class="token punctuation">.length<span class="token punctuation">; i<span class="token operator">++<span class="token punctuation">) <span class="token punctuation">{<br/><span class="token keyword">var seg <span class="token operator">= segs<span class="token punctuation">[i<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">== seg<span class="token punctuation">) path<span class="token punctuation">.<span class="token function">pop<span class="token punctuation">(<span class="token punctuation">)<span class="token punctuation">;<br/><span class="token keyword">else <span class="token keyword">if <span class="token punctuation">(<span class="token string">'.' <span class="token operator">!<span class="token operator">= seg<span class="token punctuation">) path<span class="token punctuation">.<span class="token function">push<span class="token punctuation">(seg<span class="token punctuation">)<span class="token punctuation">;<br/><span class="token punctuation">}<br/><br/><span class="token keyword">return <span class="token function">require<span class="token punctuation">(path<span class="token punctuation">.<span class="token function">join<span class="token punctuation">(<span class="token string">'/'<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">}<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></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></span></span></span></span></span></span></code></span></code>
<span style="font-family:'Microsoft YaHei';font-size:16px;"><code class="language-html"><br/><script src="require.js" /><br/><br/><script><br/>require.register("moduleId", function(module, exports, require){<br/> // Module code goes here<br/>});<br/>var result = require("moduleId");<br/></script><br/></code></span>
<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
是同步的。
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. ##
##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:
##
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:
##
Latest Articles by Author
2018-08-10 17:53:11 2018-08-10 17:50:08 2018-08-10 17:44:54 2018-08-10 17:21:11 2018-08-10 17:11:46 2018-08-10 16:56:16 2018-08-10 16:51:55 2018-08-10 16:35:09 2018-08-10 16:16:37 2018-08-10 15:43:58Latest IssuesHow to display the mobile version of Google Chrome Hello teacher, how can I change Google Chrome into a mobile version?From 2024-04-23 00:22:190112520There is no output in the parent window document.onclick = function(){ window.opener.document.write('I am the output of the child ...From 2024-04-18 23:52:34012015