简化的 commonJS 包装器如何在 require.js 中工作?

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

考虑他们网站上的这个例子

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

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

我的问题是,'foo'是异步加载的,它下面的Javascript怎么没加载完就不执行了?

这在 http://requirejs.org/docs/api.html#cjsmodule and http://requirejs.org/docs/whyamd.html#sugar 中有解释。

Require.js 会在某个时候(在 运行 函数之前)查看函数的 字符串表示形式 ,找到所有 require调用以确定依赖项并加载它们。

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.