Modular
Maintainability and reuse
What is AMD/CMD and the difference?
CommonJS is a specification Nodejs is the implementation of this specification
AMD/CMD is born from
commonjs seajs Follow the CMD specification
requirejs Follow AMD's specification
AMD Asynchronous module definition advance execution dependency pre-
CMD General module definition delayed execution dependency nearby (according to Need to load) Advantages: no waste of resources Disadvantages: long waiting time
AMD usage
<!---->
<h1></h1>
<script src="require.js" data-main="js/main"></script>
//定义模块 /test/a.js(公共)
define(function(){
var str_a = 'hello wrold';
return str_a;
})
//定义模块 /demo.js(公共)
define(function(reqire,exports,module){
/*
var demo = function(){
return 123
};
return {
demo:demo
};
*/
//字面量
var web = {
add:function(v){
return v
}
};
//return web;
//模块导出 与return web结果一样,只是写法不一样;
module.exports = web;
})
//AMD / CMD 规范
//AMD 依赖前置
define(['todo'],function(){
var t = todo.dotosomething();
var web = function(){
add:function(v,t){
return v+t
}
}
return web;
})
//CMD 依赖就近
/*
define(function(require,exports,module){
var todo = requuire("todo");
var t = todo.dotosomething();
var web = {
add:function(v){
return v
}
};
return web;
})
*/
//todo.js
define(function(){
var dotosomething = function(){
return 100
};
return {
dotosomething:dotosomething
}
})
//main.js a:别名
require.config({
// baseUrl:"node_modules",//全局定义
shim:{
//非AMD模块输出,继承AMD的规范
"bootstrap":{
deps:["jquery"],//表示有依赖关系
exports:"bootstrap"//名称
}
},
paths:{
"jquery":"../node_modules/jquery",
//"jquery":"/jquery",//使用baseUrl
"bootstrap":"../node_modules/bootstrap",
"a":"test/a",
"demo":"demo"
}
})
//require(['../jquery','../bootstrap','test/a'],function($,bootstrap,a){//路径太长 不推荐
require(['jquery','bootstrap','a','demo'],function($,bootstrap,a){
//别名要一一对应
console.log(a)//hello wrold
// document.querySelector("h1").innerHTML = a;
$("h1").text(a);
console.log(demo.demo(1000))
})
Multiple requests: Promise chain writing