2013-07-08 72 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;}));