1. 程式人生 > 實用技巧 >JS的各種模組化規範

JS的各種模組化規範

AMD CMD CommonJs UMD ES6 一路演進

AMD

  • 非同步模組定義規範(Asynchronous Module Definition),人如其名,是非同步載入的
  • 是運行於瀏覽器之上的
  • 此規範只有一個 API,即 define 函式:define(id?, dependencies?, factory);
  • requireJs 就是它的實現
  • 示例:
// moudle-a.js
define('moudleA', function() { 
    return {
        a: 1
    }
});

// moudle-b.js
define(['moudleA'], function(ma) {
    var b = ma.a + 2;

    return {
        b: b
    }
});

CMD

  • 通用模組定義規範(Common Module Definiton)
  • 更簡單,非同步載入指令碼,相容 Nodejs
  • 定義格式: define(factory);
  • SeaJS 是它的實現
  • 示例:
// moudle-a.js
define(function(require, exports, module) {

    module.exports = { 
        a: 1 
    };

});

// moudle-b.js
define(function(require, exports, module) {

    var ma = require('./moudle-a');
    var b = ma.a + 2;
    module.exports = { 
        b: b 
    };
});

CommonJs

  • 通常用於服務端的 Nodejs 中
  • 每一個檔案就是一個模組
  • module 代表當前模組,module.exports 是對外的介面; require 方法用於載入模組
  • 示例:
//moudle-a.js
moudle.exports = {
    a: 1
};

//moudle-b.js
var ma = require('./moudle-a');
var b = ma.a + 2;
module.exports ={
    b: b
};

UMD

  • 通用模組定義規範(Universal Module Definition)
  • 它可以通過 執行時或者編譯時 讓同一個程式碼模組在使用 CommonJs、CMD 甚至是 AMD 的專案中執行
  • 它沒有自己的專有規範,它是在定義模組的時候檢測當前使用環境和模組的定義方式,將各種模組化定義方式轉化為同樣一種寫法
  • 示例(元件庫 xmh 的 webpack umd 匯出為例):
function(e, t) {
    "object" == typeof exports && "object" == typeof module 
    ? module.exports = t() 
    : "function" == typeof define && define.amd 
        ? define([], t) 
        : "object" == typeof exports 
            ? exports.xmh = t() 
            : e.xmh = t()
} (window, (function() {
    // todo
}))

ES6 模組

  • ES6 終於從語言層面定義了模組化規範
  • import 載入模組,export 匯出模組
  • 示例:
//module-a.js
export default {
    a: 1
}

//module-b.js
import { a } from './module-a'
export const b = a + 2