js模块开发兼容exports

转自:https://www.cnblogs.com/CyLee/p/6422804.html

常用:

(function () {})(); 

// 小技巧(如果不加上!会报错,加上之后还能返回true呢。)
// 但由于衡返回true。所以只有某些函数是只执行,不在于返回结果的可以用这种。
;!function(){};

方式1:
(function (root, factory) {
  if (typeof exports === "object") {
    module.exports = factory();
  } else if (typeof define === "function" && define.amd) {
    define([], factory);
  } else {
    root.ol = factory();
  }
}(this,function () {
  // ...  这里编写你的代码
  return {
      
   };
})

方式2:

(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`.
        // e.g. var jQuery = require("jquery")(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 {
        factory( global );
    }

// Pass this if window is not defined yet
})( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

    //... 这里编写你的代码,例如:
    if ( !noGlobal ) {
        window.jQuery = window.$ = jQuery;
    }

    return jQuery;
})

方式3:
"use strict";
(function(exports, undefined) {
    var ns = exports.Best = exports.Best || {};
    
    /***************************/
    /********** Game **********/
    /***************************/
    var Game = ns.Game = function(options) {
        for (var p in options) {
            this[p] = options[p]
        }
    };
    Game.prototype = {};

    /***************************/
    /********** Scene **********/
    /***************************/
    var Scene = ns.Scene = function(options) {
        for (var p in options) {
            this[p] = options[p]
        }
    };
    Scene.prototype = {};
})(this);

// index.js
var game = new Best.Game({
  // some options...
});
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注