【问题标题】:What are the best practices to make a plugin CJS, AMD, and script-tag friendly to also be CJS/AMD/script-tag ready?使插件 CJS、AMD 和 script-tag 友好以也准备好 CJS/AMD/script-tag 的最佳实践是什么?
【发布时间】:2013-02-22 04:18:17
【问题描述】:

我正在尝试为几乎可以在任何地方使用的库 (MomentJS) 编写插件。我打算将它与 RequireJS 一起使用,所以它必须是 AMD 友好的,但我也想继续让那些通过浏览器或 Node 中的脚本标签加载它的人使用它。

闲逛之后,我把这个拍在了一起:

(function() {
    var hasModule = typeof module !== "undefined"  && module.exports;

    var MY_LIB_DEF = function (moment, global) {
        if(typeof moment == "undefined") {
            throw "Can't find moment";
        }

        var MY_LIB = {
            //
            //DEFINE PLUGIN
            //
        };

        if(hasModule) {
            module.exports = LIB
        } else if(global) {
            global.LIB = LIB;
        } else {
            return LIB;
        }
    };

    if(hasModule) {
        moment = require('moment');
    }

    if (typeof define === "function" && define.amd) {
        define(["moment"], MY_LIB_DEF);
    } else {
        MY_LIB_DEF(moment, this);
    }
})();

MY_LIB_DEF 的底部,我确定是为 CJS 导出、附加到窗口还是为 AMD 返回似乎有点笨拙,就像我选择启动的方式一样(CJS 和脚本加载将共享运行定义函数。但是传递给它的“全局”永远不会被使用)。

虽然上述方法有效,但我认为这个问题必须已经解决了。我似乎找不到任何可以效仿的例子。

有人知道这方面的更好做法吗?

【问题讨论】:

    标签: javascript requirejs amd commonjs


    【解决方案1】:

    四处寻找,我找到了一些good info here来帮助解决问题。为了我的目的,仍然需要稍微按摩一下,但这似乎是解决方案。

    (function(root, definition) {
        "use strict";
        var moment;
    
        if (typeof module !== 'undefined' && module.exports) {
            moment = require('moment');
            module.exports = definition(moment);
        } else if (typeof define === 'function' && define.amd){
            define(['moment'], definition);
        } else {
            root['MY_LIB'] = definition(root.moment);
        }
    }(this, function(moment) {
        if(typeof moment === "undefined") {
            throw "Can't find moment";
        }
        return {
            foo: function() {
                console.log('bar');
            }
        };
    }));
    

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2017-02-25
      • 2011-09-25
      • 1970-01-01
      • 2010-09-15
      • 2015-10-06
      相关资源
      最近更新 更多