模块化概念
AMD是requirejs在推广过程中对模块化定义的规范化产出。
异步加载模块,依赖前置,提前执行
Define定义模块define(['require','foo'],function(){return});
Require加载模块(依赖前置)require(['foo','bar'],function(foo,bar){});
CMD是SeaJS在推广过程中对模块化定义的规范化产出。
Define定义exports导出define(function(require,exports,module){});
module上存储了当前模块上的一些对象。
require(./a)直接引入,require.async异步引入
同步加载,依赖就近,延迟执行
类似的还有CommonjsModule/2.0规范
AMD模块化的代码
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script data-main="js/main.js" src="./js/require.js"></script>
</head>
<body>
<script>
</script>
</body>
</html>
//main.js
define(['require','main'],function(require){
require(['index','test'],function(index,test){
console.log(index());
console.log(test());
})
})
//index.js
define(['require','index'],function(require){
var index = function(){
console.log('test index');
}
return index;
})
//test.js
define(['require','index'],function(require){
var init = function(){
console.log('test init');
}
return init;
})
方法调用的方式
//index.js
define(['require','index'],function(require){
var index = {};
var index = {
init:function(){
console.log('test init');
}
}
return index;
})
//main.js
define(['require','main'],function(require){
require(['index','test'],function(index,test){
console.log(index.init());
console.log(test.init());
})
})
//test.js
define(['require','index'],function(require){
var index = {};
var index = {
init:function(){
console.log('test init');
}
}
return index;
})
效果为
seajs的应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/sea.js"></script>
</head>
<body>
<script>
// seajs 的简单配置
seajs.config({
base: "./js/",
alias: {
"jquery": "jquery.js"
}
})
// 加载入口模块
seajs.use("main")
</script>
</body>
</html>
//index.js
define(function(require,exports,module){
// 透过exports对外提供接口
// exports.doSomething = function(){
// console.log('my ok ');
// }
// exports.doSomething2 = function(){
// console.log('my ok2 ');
// }
var a = {};
a.doSomething = function(){
console.log('my ok ');
}
a.doSomething2 = function(){
console.log('my ok2 ');
}
// console.log(module);
module.exports = a;
});
//main.js
define(function(require,exports,module){
require('jquery');
console.log('..aaa');
var index =require.async('index',function(index){
console.log(index);
});
})
本文看自前端常用的库和实用技术之JavaScript 模块化视频