Skip to content

Commit 940edb6

Browse files
committed
add amd cmd
1 parent a86e4fb commit 940edb6

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

CommonJS/cmd_Amd.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
### 定义: ###
2+
3+
异步模块定义(AMD)是Asynchronous Module Definition的缩写,是 RequireJS 在推广过程中对模块定义的规范化产出。规范传送门
4+
通用模块定义(CMD)是Common Module Definition的缩写,是SeaJS 在推广过程中对模块定义的规范化产出。规范传送门
5+
6+
### 区别: ###
7+
8+
1. 对于依赖的模块,AMD 是提前执行,CMD 是延迟执行。不过 RequireJS 从 2.0 开始,也改成可以延迟执行(根据写法不同,处理方式不同)。CMD 推崇 as lazy as possible.
9+
10+
2. CMD 推崇依赖就近,AMD 推崇依赖前置。看代码:
11+
12+
// CMD
13+
define(function(require, exports, module) {
14+
var a = require('./a')
15+
a.doSomething()
16+
// 此处略去 100 行
17+
var b = require('./b') // 依赖可以就近书写
18+
b.doSomething()
19+
// ...
20+
})
21+
22+
// AMD 默认推荐的是
23+
define(['./a', './b'], function(a, b) { // 依赖必须一开始就写好
24+
a.doSomething()
25+
// 此处略去 100 行
26+
b.doSomething()
27+
...
28+
})
29+
30+
虽然 AMD 也支持 CMD 的写法,同时还支持将 require 作为依赖项传递,但 RequireJS 的作者默认是最喜欢上面的写法,也是官方文档里默认的模块定义写法。
31+
32+
33+
3. AMD 的 API 默认是一个当多个用,CMD 的 API 严格区分,推崇职责单一。比如 AMD 里,require 分全局 require 和局部 require,都叫 require。CMD 里,没有全局 require,而是根据模块系统的完备性,提供 seajs.use 来实现模块系统的加载启动。CMD 里,每个 API 都简单纯粹。
34+
35+
36+
4. 还有一些细节差异,具体看这个规范的定义就好,就不多说了。
37+
38+
另外,SeaJS 和 RequireJS 的差异,可以参考:https://github.com/seajs/seajs/issues/277
39+
40+
比较 NodeJS 和 SeaJS 在模块机制上的异同
41+
42+
### 比较两者在模块环境上的区别。 ###
43+
44+
已知差异点:
45+
>
46+
NodeJS 里,模块文件里的 this === module.exports;
47+
SeaJS 里,this === window。
48+
NodeJS 里,模块文件里的 return xx 会被忽略;
49+
SeaJS 里,return xx 等价 module.exports = xx。
50+
NodeJS 里,require 是懒加载 + 懒执行的。在 SeaJS 里是提前加载好 + 懒执行。
51+
SeaJS 里,require(id) 中的 id 必须是字符串直接量。NodeJS 里没这个限制。
52+
53+
参考:https://github.com/seajs/seajs/issues/141

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,15 @@ Observer-Pattern
111111
1 function前加操作符
112112

113113
<h3 name="Module"> javascript 模块化规范</h3>
114-
<h4>1. AMD</h4>
115-
<h4>2. CommonJS</h4>
114+
<h4>1. AMD</h4>
115+
>[https://github.com/wchaowu/javascript-code/tree/](https://github.com/wchaowu/javascript-code/tree/ "https://github.com/wchaowu/javascript-code/tree/")master/AMD
116+
<h4>2. CommonJS</h4>
117+
>[https://github.com/wchaowu/javascript-code/tree/master/CommonJS](https://github.com/wchaowu/javascript-code/tree/master/CommonJS "https://github.com/wchaowu/javascript-code/tree/master/CommonJS")
118+
116119
<h3 name="html5">HTML5<h5>
120+
Canvas
117121
<h3 name="NodeJs">Node.js</h3>
122+
118123
------------------------
119124
## 推荐学习资源 ##
120125

0 commit comments

Comments
 (0)