With AMD modules, when (or why) is it OK to use require() within define()?

六月ゝ 毕业季﹏ 提交于 2019-12-02 18:40:20
unscriptable

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 to require is a global. You want a reference to a require that is scoped to the context of your module (sometimes called a "local require"). This is easy:

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 */ 
}); 

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:

  1. you don't know which modules are needed at build time (or at load time) due to run-time conditions
  2. you explicitly want to defer loading of some modules until they're needed
  3. you want to load a variation of a module based on results of feature detection (although something like dojo's "has!" plugin might be a better solution ( sorry, link eluding me))

Lastly, AMD defines a second usage of require for compatibility with modules authored in the CommonJS Modules/1.1 which are then wrapped in a define. These look like this:

define(function(require, exports, module){ 
    var a = require("pkgZ/moduleA"), // dependency
        b = require("pkgZ/moduleB"); // dependency
    /* rest of the code for this module */ 
}); 

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!