使我的javascript函数requirejs/amd友好

make my javascript function requirejs/amd friendly?

本文关键字:amd 友好 requirejs 函数 我的 javascript      更新时间:2023-09-26

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

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

这就是它的样子:

文件名:myfunction.js

代码:

myfunction = function() {
   ...
};

如何使我的库符合amd和require.js?

Requirejs文档告诉您如何制作符合AMD的模块。然而,在没有AMD(<script>标签)的情况下使用时,很难找到关于如何保持模块工作的信息。无论如何,在Requirrejs上下文中,定义了"define"方法。否则,下面的示例只使用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

我发现了一篇很好的帖子,解释了整个过程。

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