对于 AMD 模块,什么时候(或为什么)可以在 Define() 中使用 require() ?

2024-03-20

我对AMD模块(例如使用RequireJs或curl.js)的理解是:

require()用于异步加载不同的模块,加载后执行回调 fn。

要定义模块,您将有单独的脚本使用define()

但我见过一些模块使用require()在它们的函数定义中,例如

define([a, b, c], function(i, ii, iii){ 
    require([d, e, f], function(d, e, f) {
        // do some stuff with these require()'d dependancies
    })
    /* rest of the code for this module */ 
}) 

但我发现这令人困惑,因为我认为如果一个模块具有依赖项,那么它们应该通过主函数传递define([dependancies], fnDefinition)函数而不是在其中通过require()按照上面的例子正在做的。

这背后有原因吗?


您可能想要使用以下几个原因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:

  1. 由于运行时条件,您不知道构建时(或加载时)需要哪些模块
  2. 您明确希望推迟某些模块的加载,直到需要它们为止
  3. 您想要根据功能检测的结果加载模块的变体(尽管像 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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对于 AMD 模块,什么时候(或为什么)可以在 Define() 中使用 require() ? 的相关文章

随机推荐