2014-04-03 86 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