2014-04-03 84 views
0

我想使用類似requireJS到modularise我的JavaScript的應用程序,但是,有一個特別的要求,我想見見我還沒有想通了:封裝requireJS及其模塊

我足夠滿意requiredefine在全球空間,但是,我希望模塊,我導入require全球可訪問(即他們應該可以訪問我的應用程序,但不能在同一頁上運行的其他應用程序)。

在我看來,如果我打電話define('moduleA', function() { ... });我可以通過require函數訪問該模塊 - 全局 - 。它可能不會佔用全局空間本身的一個變量,或者附加到window,但它仍然感覺不好,因爲其他應用程序確實不應該能夠看到我的內部模塊(更不用說潛在的命名衝突等) ,我可以使用contexts來規避這種情況嗎?)。

這似乎是從命名空間模塊退後一步,並將它們全部包含在構建時的一個大型私有化函數中。

我可以有我自己的私人版本require但我的模塊(在不同的文件中)將無法訪問define

我錯過了什麼,或者我只需要忍受這一點? (或者,也可以運行優化器將所有內容燒寫到一個文件中 - 感覺就像我只是命名空間模塊一樣,如果我這樣做的話,根本就不用打擾requireJS)。

回答

0

在您的r.js構建配置中添加wrap: true,您將不再使用requiredefine函數污染glabal範圍。

編輯

你也可以指定一個命名空間爲您的requiredefine與在r.js的namespace設置構建的配置。你可以read more about namespacing in RequireJS's FAQ。從example.build.js評論:

// Allows namespacing requirejs, require and define calls to a new name. 
// This allows stronger assurances of getting a module space that will 
// not interfere with others using a define/require AMD-based module 
// system. The example below will rename define() calls to foo.define(). 
// See http://requirejs.org/docs/faq-advanced.html#rename for a more 
// complete example. 
namespace: 'foo', 
+0

包裝require/define很容易,但然後我的模塊無法看到它們(從其他文件加載時)。 – Rhys

+0

@Ryven看到我的編輯。 – idbehold