1. 程式人生 > >什麼是AMD,CommonJS,UMD(2)

什麼是AMD,CommonJS,UMD(2)

模組規範

JS元件生態系統穩步增加,但是元件之間互相引入導致元件混亂,為了解決問題,互為對手的AMD和CommonJS出現,他們可以讓開發者在約定的沙箱以模組化的形式編寫自己的程式碼。

AMD 非同步模組定義

RequireJS目前是現在最流行的實現方式

例如foo模組依賴於jquery

//    filename: foo.js
define(['jquery'], function ($) {
    //    methods
    function myFunc(){};

    //    exposed public methods
    return myFunc;
});

//    filename: foo.js
define(['jquery', 'underscore'], function ($, _) {
    //    methods
    function a(){};    //    private because it's not returned (see below)
    function b(){};    //    public because it's returned
    function c(){};    //    public because it's returned

    //    exposed public methods
    return {
        b: b,
        c: c
    }
});

CommonJS

如果你使用過Node.js,就會對Commonjs熟悉,這已經成為瀏覽器開發前端的一種趨勢
例子如下:

var $ = require('jquery');
function muFunc(){};
module.exports = myFunc;
//    filename: foo.js
var $ = require('jquery');
var _ = require('underscore');

//    methods
function a(){};    //    private because it's omitted from module.exports (see below)
function b(){};    //    public because it's defined in module.exports
function c(){};    //    public because it's defined in module.exports

//    exposed public methods
module.exports = {
    b: b,
    c: c
};

UMD:通用模組定義

由於AMD和CommonJS沒有達成共識,所以需要一種支援兩個風格的模式,
UMD不但支援AMD和CommonJS,而且支援global,通過webpack轉義之後生成

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals (root is window)
        root.returnExports = factory(root.jQuery);
    }
}(this, function ($) {
    //    methods
    function myFunc(){};

    //    exposed public method
    return myFunc;
}));
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery', 'underscore'], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS-like
            module.exports = factory(require('jquery'), require('underscore'));
    } else {
        // Browser globals (root is window)
        root.returnExports = factory(root.jQuery, root._);
    }
}(this, function ($, _) {
    //    methods
    function a(){};    //    private because it's not returned (see below)
    function b(){};    //    public because it's returned
    function c(){};    //    public because it's returned

    //    exposed public methods
    return {
        b: b,
        c: c
    }
}));

CMD 普通模組規範

image