3. AMD规范与CommonJS规范的兼容性
- CommonJS规范加载模块是同步的,也就是说,只有加载完成,才能执行后面的操作。
- AMD规范则是非同步加载模块,允许指定回调函数。
- 由于Node.js主要用于服务器编程,模块文件一般已经存在于本地硬盘,所以加载起来比较快,不用考虑非同步加载的方式,所以CommonJS规范比较适用。
- 如果是浏览器环境,要从服务器端加载模块,这时就必须采用非同步模式,因此浏览器一般适用AMD规范。
AMD规范适用define方法定义模块,下面就是一个例子
define(["package/lib"],function(lib){
function foo(){
lib.log('hello world');
}
return { foo };
});
AMD规范允许输出的模块兼容CommonJS规范,这时define方法需要写成这样
define(function(require,exports,mould){
var someModule = require('someModule');
var anotherModule = require('anotherModule');
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
exports.asplode = function(){
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
};
})