什么是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 普通模块规范

什么是AMD,CommonJS,UMD(2)_第1张图片

你可能感兴趣的:(前端)