相容amd,commonjs和browser的模組寫法

看風景就發表於2015-10-30

從uuid.js中抽出來的寫法。

(function() {
  var _global = this;

  // Export public API
  var obj = {};
  obj.attr = function(params){

  };

  if (typeof define === 'function' && define.amd) {
    // Publish as AMD module
    define(function() {return obj;});
  }

  else if (typeof(module) != 'undefined' && module.exports) {

    // Publish as commonjs module
    module.exports = obj;
  }

  else {
    // Publish as global (in browsers)
    var _previousRoot = _global.obj;

    // **`noConflict()` - (browser only) to reset global 'obj' var**
    obj.noConflict = function() {
      _global.obj = _previousRoot;
      return obj;
    };

    _global.obj = obj;
  }
}).call(this);

 

相關文章