2013-07-08 39 views
4

我已经创建了一个JavaScript库,它只向全局空间添加一个全局对象。让我的javascript函数requirejs/amd友好?

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

这是它的外观:

文件名: myfunction.js

代码:

myfunction = function() { 
    ... 
}; 

如何让我的库符合AMD和require.js?

回答

9

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

0

我发现了一个伟大的职位,解释了整个过程。

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;}));