4

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

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

这是它的外观:

文件名: myfunction.js

代码:

myfunction = function() {
   ...
};

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

4

2 回答 2

10

Requirejs 文档告诉你如何制作一个兼容 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

于 2013-07-08T11:24:52.370 回答
1

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

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;}));
于 2016-07-08T12:31:25.533 回答