【问题标题】:make my javascript function requirejs/amd friendly? [duplicate]让我的 javascript 函数对 requirejs/amd 友好? [复制]
【发布时间】:2013-07-08 10:29:05
【问题描述】:

我创建了一个 javascript 库,它只将一个全局对象添加到全局空间。

全局对象恰好是一个函数,函数名与文件名匹配。

看起来是这样的:

文件名: myfunction.js

代码:

myfunction = function() {
   ...
};

如何使我的库与 amd 和 require.js 兼容?

【问题讨论】:

标签: javascript requirejs amd


【解决方案1】:

The Requirejs Docs 告诉您如何制作符合 AMD 标准的模块。但是,在没有 AMD(<script> 标签)的情况下如何保持模块工作的信息在那里很难找到。无论如何,在 Requrirejs 上下文中,定义了“定义”方法。否则,下面的示例仅使用 window.x(不是最优雅的解决方案)将函数从闭包内暴露给全局空间。

(function (module) {
    if (typeof define === "function" && define.amd) {
        define(function () { return module; });
    } else {
        window.myfunction = module.myfunction;
    }
}({
    myfunction: function () {
        /* ... */
    }
}));

另见:https://stackoverflow.com/a/14033636

【讨论】:

    【解决方案2】:

    我找到了一个很好的帖子来解释整个过程。

    http://ifandelse.com/its-not-hard-making-your-library-support-amd-and-commonjs/

    简而言之,作者提出了以下模式:

    ** 这里,postal.js 是一个 AMD/Commonjs 兼容的模块。

    (function (root, factory) {
    
    if(typeof define === "function" && define.amd) {
    // Now we're wrapping the factory and assigning the return
    // value to the root (window) and returning it as well to
    // the AMD loader.
    define(["postal"], function(postal){
      return (root.myModule = factory(postal));
    });
    } else if(typeof module === "object" && module.exports) { 
    // I've not encountered a need for this yet, since I haven't
    // run into a scenario where plain modules depend on CommonJS
    // *and* I happen to be loading in a CJS browser environment
    // but I'm including it for the sake of being thorough
    module.exports = (root.myModule = factory(require("postal")));
    } 
    else {   //node.js diverges from the CommonJS spec a bit by using module.  So, to use it in other common js environments
    root.myModule = factory(root.postal);}}(this, function(postal) {//passing this as the root argument, and our module method from earlier as the factory argument. If we run this in the browser, this, will be the window.
    
     var sub;
       var ch = postal.channel("myModule");
       var myModule = {
         sayHi:function() {
                ch.publish("hey.yall", { msg: "myModule sez hai" });
         },
         dispose: function() {
                sub.unsubscribe();
         }};return myModule;}));
    

    【讨论】:

    • 非常棒的教程,感谢发帖
    • @BasheerAL-MOMANI 很高兴它对您有所帮助。可以点赞!!!大声笑。
    猜你喜欢
    • 2013-04-19
    • 2014-06-04
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2017-10-30
    • 2012-04-14
    • 2013-12-26
    相关资源
    最近更新 更多