UMD、CommonJS、ES Module、AMD、CMD模塊的寫法


AMD異步模塊規范

RequireJS就是AMD的一個典型的實現。

以下是一個只依賴與jQuery的模塊代碼:

// foo.js
 
define(['jquery'], function($){  //此為工廠函數 function myFunc(){};
 
    // 暴露公共方法
    return myFunc;
})
define(['jquery', 'underscore'], function($, _){
    function a(){};     // 私有方法,沒有被返回
    function b(){};
    function c(){};
 
    // 暴露公共方法
    return {
        b: b,
        c: c
    }
})

CMD (Common Module Definition)

define(function(require, exports, module) {
    var a = require('./a')
    var b = require('./b') // 依賴可以就近書寫
 
    // 通過 exports 對外提供接口
    exports.doSomething = function(){}
 
    // 或者通過 module.exports 提供整個接口
    module.exports = {}
})
<script src="sea.js"></script>
<script>
seajs.use('dialog', function(Dialog) {
  Dialog.init(/* 傳入配置 */);
});
</script>

Sea.js 還提供了 nocache、debug 等插件,擁有在線調試等功能,能比較明顯地提升效率。
Sea.js 還提供了 combo、flush 等插件,配合服務端,可以很好地對頁面性能進行調優。
CMD 模塊定義規范與 Node.js 的模塊規范非常相近。通過 Sea.js 的 Node.js 版本,可以很方便實現模塊的跨服務器和瀏覽器共享。

CommonJS

與node.js的格式非常相似。可配合Browserify進行使用。

Browserify 可以讓你使用類似於 node 的 require() 的方式來組織瀏覽器端的 Javascript 代碼,通過預編譯讓前端 Javascript 可以直接使用 Node NPM 安裝的一些庫。

// foo.js
 
var $ = require('jquery');
function myFunc(){};
 
module.exports = myFunc;
var $ = require('jquery');
var _ = require('underscore');
 
function a(){}; // 私有
function b(){};
function c(){};
 
module.exports = {
    b: b,
    c: c
}

UMD通用模塊規范

由於CommonJS和AMD都十分流行,但似乎缺少一個統一的規范。於是,UMD(通用模塊規范)出現了,它可以同時支持這兩種風格。

雖然這個模式的寫法比較難看,但是,它同時兼容了AMD和CommonJS,而且還支持老式的全局變量規范。

UMD:Universal Module Definition(通用模塊規范)是由社區想出來的一種整合了CommonJS和AMD兩個模塊定義規范的方法。

基本原理

用一個工廠函數來統一不同的模塊定義規范。

原則

  • 所有定義模塊的方法需要單獨傳入依賴
  • 所有定義模塊的方法都需要返回一個對象,供其他模塊使用
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node, CommonJS之類的
    module.exports = factory(require('jquery'));
  } else {
    // 瀏覽器全局變量(root 即 window)
    root.returnExports = factory(root.jQuery);
  }
}(this, function ($) {
  //    方法
  function myFunc(){};
 
  //    暴露公共方法
  return myFunc;
}));

例如,利用UMD定義一個toggler模塊:

(function (global, factory) {
    if (typeof exports === 'object' && typeof module !== undefined) { //檢查CommonJS是否可用
        module.exports = factory(require('jquery'));
    } else if (typeof define === 'function' && define.amd) {      //檢查AMD是否可用
        define('toggler', ['jquery', factory])
    } else {       //兩種都不能用,把模塊添加到JavaScript的全局命名空間中。
        global.toggler = factory(global, factory);
    }
})(this, function ($) {
    function init() {

    }
    return {
        init: init
    }
});

ES Module

// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
 
export {firstName, lastName, year};
//import obj from ‘xxx 只會導出這個默認的對象作為一個對象obj,
//
main.js import {firstName, lastName, year} from './profile'; function setName(element) { element.textContent = firstName + ' ' + lastName; }

再例如整體加載模塊

// circle.js
 
export function area(radius) {
  return Math.PI * radius * radius;
}
export function circumference(radius) {
  return 2 * Math.PI * radius;
}
//注釋:import * as obj from ‘xxx’會將 若干export導出的內容組合成一個對象obj返回;
import * as circle from './circle'; console.log('圓面積:' + circle.area(4)); console.log('圓周長:' + circle.circumference(14));
// export-default.js
export default function () {
  console.log('foo');
}
 

(支持amd、cmd、commonjs規范的模塊加載) 即UMD

;(function( global, factory ){

    "use strict";

    if ( typeof module === "object" && typeof module.exports === "object" ) {
    
        // For CommonJS and CommonJS-like environments where a proper `window`
        // is present, execute the factory and get jQuery.
        // For environments that do not have a `window` with a `document`
        // (such as Node.js), expose a factory as module.exports.
        // This accentuates the need for the creation of a real `window`.
        // See ticket #14549 for more info.
        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };
    } else if (define && define.cmd) {
        define( function () {
                return factory(global);
        } );
    } else {
        factory( global );
    }

})( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

    // 核心邏輯代碼...

    // 使代碼支持 amd 模塊加載
    if ( typeof define === "function" && define.amd ) {
        define( "jquery", [], function() {
            return jQuery;
        } );
    }

    return {
      add: function(a, b) { return a + b }
    }

})
--------------------- 
參考:https://blog.csdn.net/Jacoh/article/details/85720146 

參考:http://www.jianshu.com/p/ba6a24dc6b23

 https://www.4455q.com/tech/umd_commonjs_es-module_amd.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM