文章序
總是會(huì)看到前端模塊化的這幾個(gè)技術(shù)角塑,今天一次性整理,如有錯(cuò)誤歡迎評(píng)論指正淘讥!
AMD
異步加載圃伶,依賴前置,前置依賴建議寫(xiě)在前引用,在所有模塊加載完成后立即執(zhí)行回調(diào)函數(shù)留攒,用戶體驗(yàn)好煤惩,不容易造成卡頓
需要引用require.js
//math.js
define([], function () {
function add(a, b) {
return a + b;
}
return { add };
});
//main.js
require(["./math.js"], function(mathObj) {
res = mathObj.add(5, 6);
console.log(res);
})
//index.html
<html>
<body></body>
</html>
<script src="./require.js"></script>
<script src="./main.js"></script>
//控制臺(tái)打印11
CMD
異步加載,依賴就近炼邀,按需加載魄揉,在require引用的地方執(zhí)行代碼,性能好
需要引用sea.js
//math.js
define(function (require, exports, module) {
function add(a, b) {
return a + b;
}
exports.add = add;
});
//main.js
define(function (require, exports, module) {
const add = require('./math');
const res = add(5, 6);
console.log(res);
});
//index.html
<html>
<body></body>
</html>
<script src="./sea.js"></script>
<script src="./main.js"></script>
//控制臺(tái)打印11
CommonJs
同步加載拭宁,運(yùn)行時(shí)加載執(zhí)行洛退,容易阻塞進(jìn)程,造成卡頓杰标,一般用在服務(wù)端Node開(kāi)發(fā)中兵怯,輸出拷貝值,原始值改變不影響引用值
需要引用node.js
//math.js
module.exports = {
add: function(a, b) {
return a + b;
}
}
//main.js
const math = require('./math.js');
const res = math.add(1, 2);
ES6
同步加載腔剂,編譯時(shí)加載執(zhí)行媒区,因此必須放在代碼塊最頂層,輸出原始值的引用掸犬,因此原始值改變會(huì)影響引用值
需要使用ES6標(biāo)準(zhǔn)
//math.js
const add = function(a, b) {
return a + b;
}
export { add };
//main.js
import { add } from './math';
const res = add(1, 2);