定义模块并使用RequireJS立即使用它们

nic*_*ckf 9 javascript module amd requirejs

我正在为使用RequireJS的应用程序编写一些测试.由于应用程序的工作方式,它希望通过调用获得一些类require.因此,对于测试,我有一些虚拟类,但我不想将它们放入单个文件中,仅用于此测试.我更喜欢define()在我的测试文件中手动设置它们,如下所示:

define('test/foo', function () {
    return "foo";
});

define('test/bar', function () {
    return "bar";
});

test("...", function () {
    MyApp.load("test/foo"); // <-- internally, it calls require('test/foo')
});
Run Code Online (Sandbox Code Playgroud)

这里的问题是这些模块的评估被推迟,直到脚本onload事件被触发.

1600左右的require.js开始:

//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
Run Code Online (Sandbox Code Playgroud)

有什么方法可以手动触发要评估的队列吗?

kee*_*ins 0

模块定义应限制为每个文件一个(请参阅此处)。我猜测在单个文件中定义多个模块会破坏内部加载机制,该机制依赖于脚本的加载事件来确定它在解决依赖关系时是否已准备好。

即使只是为了测试,我建议将这些定义拆分为多个文件。

希望有帮助!干杯。