前端模块规范区别与应用
前端模块规范有:AMD,CMD,CommonJs,UMD
一.总览
1.浏览器端
- AMD是requireJs在推广过程中对模块定义的规范(异步模块规范)
- CMD是seaJs在推广过程中对模块定义的规范(普通模块规范)
2.node端
- commonJs(同步模块规范)
3.浏览器和node兼容端
- UMD(通用模块规范)
4.ES6内置模块化module
- import引入一个模块
- export [default] 对外暴露一个对象
二.应用
1.AMD
-
提前执行(异步加载:依赖先执行)--依赖前置
-
提供define(定义模块)和require(调用模块)方法来进行模块化编程
define(id?,dependencies?,factory);
require([module], callback);
//Utils模块
define(function(){
function Utils(name) {
this._name = name;
}
Utils.add = function(a, b) {
return a + b;
}
return Utils;
})
//加载和使用
// 配置各个模块地址
require.config({
paths: {
"Utils": "./js/lib/Utils"
},
shim: {}
});
//加载指定模块
require(["Utils"], function(Utils) {
});
2.CMD
- 延迟执行(按需加载)--依赖就近
- 在 CMD 规范中,一个模块就是一个文件
define(factory); //factory可以是个函数,也可以是个对象或字符串
define(id?, deps?, factory) //字符串id-模块标识,数组deps-依赖模块(define(function(require, exports){
//require(id) 接受 模块标识 作为唯一参数
var a = require('./a');
a.doSomething()
//require.async(id, callback?) 方法用来在模块内部异步加载模块,并支持指定回调
require.async('./b', function(b) {
b.doSomething();
});
//加载多个模块
require.async(['./c', './d'], function(c, d) {
c.doSomething();
d.doSomething();
});
//require.resolve(id)模块系统内部的路径解析机制来解析并返回模块路径
console.log(require.resolve('./b'));
// 对外提供 foo 属性
exports.foo = 'bar';
// 对外提供 doSomething 方法
exports.doSomething = function() {};
//return 直接向外提供接口
return {
foo: 'bar',
doSomething: function() {}
};
//exports 仅仅是 module.exports 的一个引用,并不会改变 module.exports 的值。因此给 exports 赋值是无效的,不能用来更改模块接口
module.exports = {
foo: 'bar',
doSomething: function() {}
};
})
3.commonJs
加载模块是同步的,只有加载完成后才能执行后面的操作
模块分为:
(1)模块引用(require)
(2)模块定义(exports)
(3)模块标识(module)
//模块
function Utils(name) {
this._name = name;
}
Utils.add = function(a, b) {
return a + b;
}
// 将类 Utils 作为当前文件的模块导出
module.exports = Utils;
//加载模块
var Utils = require('./Utils.js');
console.log(Utils.add(10, 20));