AMD and CMD

AMD CMD 规范

amd
├── index.html
├── main.js
├── module1.js
├── module2.js
├── module3.js
└── require.js

module1.js

1
2
3
4
5
6
7
8
9
define('module1',
function() {
var exports = {};
exports.say = function() {
console.log('module1 say hello');
}
return exports;
}
);

module2.js

1
2
3
4
5
6
7
8
9
define('module2',
function() {
var exports = {};
exports.say = function() {
console.log('module2 say hello')
}
return exports
}
)

module3.js AMD

1
2
3
4
5
6
7
8
9
10
11
define('module3',
['module1', 'module2'],
function(m1, m2) {
var exports = {};
exports.say = function() {
m1.say();
m2.say()
}
return exports
}
)

main.js

1
2
3
require(['module3'], function(m3) {
m3.say();
});

index.html

.html
1
<script data-main="main" src="require.js"></script>

output:
module1 say hello
module2 say hello

module3.js CMD

1
2
3
4
5
6
7
8
9
10
define(function(require, exports, module) {
var exports = {};
var m1 = require('./module1');
var m2 = require('./module2'); // 依赖可以就近书写
exports.say = function() {
m1.say();
m2.say()
};
return exports;
})

AMD和CMD的区别:

对于依赖的模块,AMD 是提前执行,CMD 是延迟执行。不过 RequireJS 从 2.0 开始,也改成可以延迟执行(根据写法不同,处理方式不同)。CMD 推崇 as lazy as possible(尽可能的懒加载,也称为延迟加载,即在需要的时候才加载)。

CMD 推崇依赖就近,AMD 推崇依赖前置。虽然 AMD 也支持 CMD 的写法,同时还支持将 require 作为依赖项传递,但 RequireJS 的作者默认是最喜欢上面的写法,也是官方文档里默认的模块定义写法。看代码:

Author: Rick
Link: https://rcrick.github.io/2020/03/21/AMDAndCMD/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶