AMD是require.js在推广过程中对模块定义的规范化产出;
CMD是sea.js在推广过程中对模块定义的规范化产出。
它们都是为了实现js在浏览器端的模块化开发,且异步加载。
其中,require.js中有全局require和局部require,而sea.js中只有局部require。
本文主要是为了记录下二者的使用,便于日后回忆使用。
目录结构
demo
|-index.html
|-index.js
|-math.js
其中,index.js为入口文件,math.js是一个用于提供加减乘除计算的独立模块。
定义模块
模块定义在math.js中,以下四种方式,任一均可。
//第一种
define(function(require,exports,module){
const add = (x,y) => x+y;
const substract = (x,y) => x-y;
const multiple = (x,y) => x*y;
const divide = (x,y) => x/y;
return{
add:add,
sub:substract,
mul:multiple,
div:divide
}
});
//第二种
define(function(require,exports,module){
const add = (x,y) => x+y;
const substract = (x,y) => x-y;
const multiple = (x,y) => x*y;
const divide = (x,y) => x/y;
module.exports = {
add:add,
sub:substract,
mul:multiple,
div:divide
}
});
//第三种
define(function(require,exports,module){
const add = (x,y) => x+y;
const substract = (x,y) => x-y;
const multiple = (x,y) => x*y;
const divide = (x,y) => x/y;
exports.add = add;
exports.sub = substract;
exports.mul = multiple;
exports.div = divide;
});
//第四种
define({
add:(x,y) => x+y,
sub:(x,y) => x-y,
mul:(x,y) => x*y,
div:(x,y) => x/y
});
使用模块之require.js
index.html中,引用require.js文件,指定入口文件为index.js。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
<script src="./require.js" data-main="./index"></script>
</head>
<body>
</body>
</html>
index.js中,调用了math.js这个模块。
//使用全局require
require(["./math.js"],function(m){
const sum = m.add(1,2);
const diff = m.sub(1,2);
console.log(sum,diff);
})
//或者 使用局部require
define(function(require,exports,module){
require(["./math.js"],function(m){
const sum = m.add(1,2);
const diff = m.sub(1,2);
console.log(sum,diff);
})
});
//或者
require.config({
baseUrl:"./",
paths:{
"m":"math"
}
});
require(["m"],function(m){
const sum = m.add(1,2);
const diff = m.sub(1,2);
console.log(sum,diff);
});
使用模块之sea.js
index.html中,引入sea.js,指定文件入口
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index3</title>
<script src="./sea.js"></script>
</head>
<body>
<script>
seajs.use("./index.js");
</script>
</body>
</html>
index.js中,调用math.js
define(function(require,exports,module){
const m = require("./math.js");
const sum = m.add(1,2);
const diff = m.sub(1,2);
console.log(sum,diff);
});
//或者
define(function(require,exports,module){
require.async(["./math.js"],function(m){
const sum = m.add(1,2);
const diff = m.sub(1,2);
console.log(sum,diff);
})
});