Skip to content
jrburke edited this page Aug 24, 2011 · 13 revisions

The require function in an AMD implementation differs from the traditional CommonJS require. There is a strong need for a callback-based require, since dynamically computed dependencies may load asynchronously.

API Specification

Local vs Global require

The local require is the require function passed to an AMD define factory function. Examples:

    define(['require'], function (require) {
        //the require in here is a local require.
    });

    define(function (require, exports, module) {
        //the require in here is a local require.
    });

The local require MAY support other APIs specific to the implementation.

A global require function is one that is available in the global scope, similar to define(). The behavior a global require is not defined by this API, and for interoperability it should not be assumed. Normally there is an implementation-dependent API that will kick of module loading.

require(String)

Synchronously returns the module export for the module ID represented by the String argument. Based on the CommonJS Modules 1.1.1 require.

It MUST throw an error if the module has not already been loaded and evaluated. In particular, the synchronous call to require MUST NOT try to dynamically fetch the module if it is not already loaded, but throw an error instead.

Dependencies can be found in an AMD module when this form of define() is used:

    define(function (require) {
        var a = require('a');
    });

The define factory function can be parsed for require('') calls (for instance by using a language parser or using Function.prototype.toString() and regexps) to find dependencies, load and execute the dependencies, then run the code above. In that manner, the require('a') call can return the module value.

require(Array, Function)

The Array is an array of String module IDs. The modules that are represented by the module IDs should be retrieved and once all the modules for those module IDs are available, the Function callback is called, passing the modules in the same order as the their IDs in the Array argument.

Example:

    define(function (require) {
        require(['a', 'b'], function (a, b) {
            //modules a and b are not available for use.
        });
    });

require.toUrl(String)

Converts a String that is of the form [module ID] + '.extension' to an URL path. require.toUrl resolves the module ID part of the string using its normal module ID-to-path resolution rules, except it does not resolve to a path with a ".js" extension. Then, the '.extension' part is then added to that resolved path. Example:

    //cart.js contents:
    define (function(require) {
        //module ID part is './tmeplates/a'
        //'.extension is '.html'
        //templatePath may end up to be something like
        //'modules/cart/templates/a.html'
        var templatePath = require.toUrl('./templates/a.html');

    });
Clone this wiki locally