您可能想要使用以下几个原因require()
在一个模块中。
但首先,请确保您请求的引用正确require
多变的。在您的示例中,引用require
is a global。您想要参考require
其范围仅限于模块的上下文(有时称为“本地需求”)。这很容易:
define(["a", "b", "c", "require"], function(i, ii, iii, require){
require(["d", "e", "f"], function(moduleD, moduleE, moduleF) {
// do some stuff with these require()'d dependencies
})
/* rest of the code for this module */
});
这很重要的主要原因是确保正确解析相对模块 ID(例如“./peerModule”或“../unclePath/cousinModule”)。 (这是原因之一,curl.js没有全局的require
默认情况下。)
使用本地的原因require
:
- 由于运行时条件,您不知道构建时(或加载时)需要哪些模块
- 您明确希望推迟某些模块的加载,直到需要它们为止
- 您想要根据功能检测的结果加载模块的变体(尽管像 dojo 的“has!”插件之类的东西可能是更好的解决方案(抱歉,链接让我困惑))
最后,AMD 定义了第二种用法require
为了与 CommonJS Modules/1.1 中编写的模块兼容,然后将其包装在define
。这些看起来像这样:
define(function(require, exports, module){
var a = require("pkgZ/moduleA"), // dependency
b = require("pkgZ/moduleB"); // dependency
/* rest of the code for this module */
});
服务器端 JavaScript 开发人员可能会发现这种格式很有吸引力。 :)
一些 AMD 加载器(例如 RequireJS 0.2+、dojo 1.7+、bdLoad 和curl.js 0.6+)将检测这种混合 AMD/CJSM1.1 格式,并通过扫描模块来查找依赖项require
calls.