module

之前node笔记中有提到关于模块的概念,在此总结一下AMD、CMD、CommonJS和es6模块。

AMD和CMD概念

之前的JavaScript没有模块这一功能,后来出现了CMDAMD这两种方式。

AMD(Asynchronous Module Definition)是 RequireJS 在推广过程中对模块定义的规范化产出。提前执行,推崇依赖前置
CMD(Common Module Definition)在推广过程中对模块定义的规范化体现是 SeaJS。延迟执行,推崇依赖就近

AMD的基本用法

1
2
3
4
5
6
7
define(id?, dependencies?, factory);
//模块的名字?,所依赖模块的数组?执行的函数或对象

define(['./a,./b'],function(a,b){
a.doSomething();
b.doSomething();
})

CMD的基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
define(id?, dependencies?, factory);
//模块的名字?,所依赖模块的数组?执行的函数或对象,不推荐带id和dependencies

define(function(require,exports,module){
var a = require("./a");
a.doSomething();
var b = require("./b")
b.doSomething();
})

// exports 是 module.exports 的引用,对外返回接口,可以通过以下方式
define(function(require,exports,module){
exports.foo = 'exports prop';
exports.doSomething = function() {//export function};
})
// 等于 return {}
define(function(require,exports,module){
return {
foo: 'exports prop',
doSomething: function() {//export function}
};
})
// 等于 module.exports
define(function(require,exports,module){
module.exports = {
foo: 'exports prop',
doSomething: function() {//export function}
};
})

CommonJS和es6模块

AMD和CMD都属于浏览器端模块开发的规范。CommonJS 是服务端的规范,Node.js 采用了这个规范。

  • CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。
  • CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。

CommonJS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// a.js
var name = 'a.js';
var fn = function (){
return console.log('this file is a.js');
}
module.exports = {
name: name,
method: fn
}

// index.js
var {name,method} = require('./a');
method();//a.js
console.log(name);//this file is a.js
//等于
var file = require('./a');
file.method();//a.js
console.log(file.name);//this file is a.js

es6模块

1
2
3
4
5
6
7
8
9
// a.js
const name = 'a.js';
let fn = () =>{ console.log('this file is a.js') }
export {name,fn as method}

// index.js
import { name,method } from './a';
method();//a.js
console.log(name);//this file is a.js

参考链接
https://github.com/seajs/seajs/issues/242
https://github.com/amdjs/amdjs-api/wiki/AMD
http://es6.ruanyifeng.com/#docs/module

------本文结束 感谢阅读------