简体   繁体   中英

How does the simplied commonJS wrapper work in require.js under the hood?

Consider this example from their website

define(function (require) {
    var foo = require('foo');

    //Define this module as exporting a function
    return function () {
        foo.doSomething();
    };
});

My question is, as 'foo' is loaded asynchronously, how does the Javascript below it not execute before it has loaded?

This is explained in http://requirejs.org/docs/api.html#cjsmodule and http://requirejs.org/docs/whyamd.html#sugar .

Require.js will at some point (before running the function) look at the string representation of the function, find all require calls to determine the dependencies and load them.

To make this easier, and to make it easy to do a simple wrapping around CommonJS modules, this form of define is supported, sometimes referred to as "simplified CommonJS wrapping":

 define(function (require) { var dependency1 = require('dependency1'), dependency2 = require('dependency2'); return function () {}; });

The AMD loader will parse out the require('') calls by using Function.prototype.toString() , then internally convert the above define call into this:

 define(['require', 'dependency1', 'dependency2'], function (require) { var dependency1 = require('dependency1'), dependency2 = require('dependency2'); return function () {}; });

This allows the loader to load dependency1 and dependency2 asynchronously, execute those dependencies, then execute this function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM