1. 程式人生 > 實用技巧 >04 CMD規範基礎使用詳解

04 CMD規範基礎使用詳解

CMD模組規範

1.1 CMD規範說明

專門用於瀏覽器端,並且模組的載入是非同步的,而且只有模組使用時才會載入執行;

CMD規範的語法類似於Commonjs + AMD ——定義模組使用AMD語法,暴露變數、引入模組使用Commonjs語法

1.2 基本語法

使用全域性函式define定義模組,使用export暴露模組,使用require引入模組

1.21暴露模組

(1)定義一個沒有依賴的模組,定義模組使用define函式,傳入一個函式,函式引數為require,exports,module,require引數用來引入模組,後面兩個引數用來暴露模組,暴露模組的方法和Commonjs規範一樣,可以使用module.exports

或者exports

// module1.js
define(function(require,exports,module){
let name = '過青年';
function getName(){
return name;
} module.exports = {name,getName};
});

(2)定義一個有依賴的模組

​ 目錄結構如下

  • 使用同步引入模組,同步可能導致堵塞
// module2.js
//同步引入
define(function(require,exports,module){
let module1 = require('./module1.js');
let age = 20;
console.log(module1.name);
console.log(module1.getName());
module.exports = {age};
})
  • 使用非同步引入模組
// module2.js
// 非同步引入
define(function(require,exports,module){
let age = 20;
// 引入模組暴露的物件作為實參傳入m1形參中
require.async('./module1.js',function(m1){
console.log(m1.name);
console.log(m1.getName());
});
module.exports = {age};
})
1.22引入模組

記住引入模組可以使用同步引入require()和非同步引入require.async()

// main.js同步引入模組
define(function(require,exports,module){
let m2 = require('./module/module2.js');
console.log(m2.age);
})
1.23在HTML頁面上使用模組化

需要引入一個叫sea.js模組載入框架,再使用另外一個script標籤,當中使用seajs.use()方法定義主模組

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AMD規範例項</title>
</head>
<body>
<script src="./js/lib/sea.js"></script>
<script>
seajs.use('./js/main.js'); /*控制檯輸出,module2.js模組中使用同步、非同步輸出差異:
同步 非同步
過青年 20
過青年 過青年
20 過青年
*/
</script>
</body>
</html>

總結

  • 使用define(function(require,exports,module){ })定義模組

  • 在定義的模組中使用module.exports或者exports暴露物件

  • 使用require()函式同步載入模組或者使用require.async()非同步載入模組

  • HTML中引入ser.js指令碼,並且再新增一個script標籤,使用serjs.use()方法指定主模組