对于 AMD 模块,什么时候(或为什么)可以在 Define() 中使用 require() ?
我对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()< /code> 按照上面的例子正在做。
这背后有原因吗?
My understanding of AMD modules (using for example RequireJs or curl.js) is:
require()
is used to asynchronously load different modules and when loaded then the callback fn is executed.
And to define a module, you would have separate scripts that use define()
But I've seen some modules use require()
inside their function definition, e.g.
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 */
})
But I find this confusing because I would have thought that if a module has dependancies then they should be passed through via the main define([dependancies], fnDefinition)
function and not within it via require()
as per the above example is doing.
Is there a reasoning behind this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能出于多种原因想要在模块中使用
require()
。但首先,请确保您请求引用正确的
require
变量。在您的示例中,对require
的引用是全局。您需要引用一个require
,其范围仅限于您的模块的上下文(有时称为“本地 require”)。这很简单:这很重要的主要原因是确保正确解析相对模块 ID(例如“./peerModule”或“../unclePath/cousinModule”)。 (这是原因之一,curl.js 默认没有全局
require
。)使用本地
require
的原因:最后,AMD 定义了
require
的第二种用法,以与 CommonJS Modules/1.1 中编写的模块兼容,然后将其包装在define
中。这些看起来像这样:服务器端 javascript 开发人员可能会发现这种格式很有吸引力。 :)
一些 AMD 加载器(例如 RequireJS 0.2+、dojo 1.7+、bdLoad 和curl.js 0.6+)将检测这种混合 AMD/CJSM1.1 格式,并通过扫描模块中的
require
来电。There are a few reasons you may want to use
require()
in a module.But first, be sure you request a reference to the correct
require
variable. In your example, the reference torequire
is a global. You want a reference to arequire
that is scoped to the context of your module (sometimes called a "local require"). This is easy:The main reason this is important is to ensure that relative module ids (e.g. "./peerModule" or "../unclePath/cousinModule") are resolved correctly. (This is one of the reasons, curl.js doesn't have a global
require
by default.)Reasons to use a local
require
:Lastly, AMD defines a second usage of
require
for compatibility with modules authored in the CommonJS Modules/1.1 which are then wrapped in adefine
. These look like this:Server-side javascript devs may find this format appealing. :)
Some AMD loaders (such as RequireJS 0.2+, dojo 1.7+, bdLoad, and curl.js 0.6+) will detect this hybrid AMD/CJSM1.1 format and find dependencies by scanning the module for
require
calls.