封装requireJS及其模块

时间:2014-04-03 20:14:02

标签: javascript requirejs

我想使用类似requireJS的内容来模块化我的javascript应用程序,但是,我想要满足的一个特殊要求是我还没想到出:

我很高兴在全球空间中拥有requiredefine,但是,我想要我导入的模块{ {1}}可以全局访问(即应该可以访问我的应用,但不能访问在同一页面上运行的其他应用)。

在我看来,如果我拨打require,我可以通过define('moduleA', function() { ... });功能全局访问该模块。它可能不会占据全局空间本身的变量,也不会附加到require,但它仍然感觉不好,因为其他应用程序真的不应该看到我的内部模块(更不用说潜在的命名冲突等,我可以使用window来规避这个吗?)。

这似乎只是命名我的模块并在构建时将它们全部包含在一个大的私有化函数中的一步。

我可以拥有自己的contexts私有版本,但我的模块(位于不同的文件中)无法访问require

我是否遗漏了某些东西,或者我只是不得不忍受这种情况? (或者,运行一个优化器将所有内容都烘焙到一个文件中 - 感觉就像我可以命名我的模块一样,如果我这样做的话,根本不会打扰define。)

1 个答案:

答案 0 :(得分:0)

在您的r.js构建配置中添加wrap: true,您将不再使用requiredefine函数污染窗体范围。

修改

您还可以在r.js构建配置中使用require设置为definenamespace指定命名空间。你可以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',