一、AMD規範
異步, 用於瀏覽器端,依賴require.js
1、基本語法
暴露模塊:
// 定義沒有依賴的模塊
define(function(){
return 模塊
})
// 定義有依賴的模塊
define(['module1','module2'],function(m1,m2){
return 模塊
})
引入使用模塊:
requirejs(['module1','module2'],function(m1,m2){
使用m1/m2
})
代碼演示:
// 無依賴模塊 dataService.js
define(function(){
let name = 'dataService.js'
function getName() {
return name
}
return {
getName
}
})
// 有依賴的模塊 alerter.js
define(['dataService'],function(dataService){
let msg = 'alerter.js'
function showMsg() {
console.log(msg, dataService.getName())
}
return {
showMsg
}
})
// 主模塊 main.js
(function(){
// 配置引用路徑
requirejs.config({
baseUrl:'./',
paths:{
dataService:'./dataService',
alerter:'./alerter'
}
})
// 引用模塊 無需再暴露用requirejs
requirejs(['alerter'],function(alerter){
alerter.showMsg()
})
})();
<!-- 主頁面 index.html -->
<body>
<script data-main="./app.js" src="require.js"></script>
</body>