【问题标题】:How does the simplied commonJS wrapper work in require.js under the hood?简化的 commonJS 包装器如何在 require.js 中工作?
【发布时间】:2016-01-07 17:03:25
【问题描述】:

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

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

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

我的问题是,由于 'foo' 是异步加载的,它下面的 Javascript 是如何在加载之前不执行的?

【问题讨论】:

标签: javascript requirejs commonjs


【解决方案1】:

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

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

为了让这更容易,并且更容易对 CommonJS 模块进行简单的包装,支持这种形式的定义,有时称为“简化的 CommonJS 包装”:

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

AMD 加载程序将使用Function.prototype.toString() 解析出require('') 调用,然后在内部将上述定义调用转换为:

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

这允许加载器异步加载dependency1dependency2,执行那些依赖,然后执行这个函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多