我在一个项目中使用了requirejs,我有两个模块:
define()函数编写的一个AMD模块。它需要a.js才能工作。a.js和b.js的实际应用程序代码。app.js看起来是这样的:
//source code for app.js
require(['a.js', 'b.js'],
function( a, b ) {
a.x = 2;//this will fail because 'a' is not defined
});现在的问题是:在require()中用app.js实现两个模块的最简单方法是什么?我不能这样做:
//source code for app.js
require(['b.js', 'a.js'],
function( b ) {
a.x = 2;//it works because module 'a' defines a global variable named 'a'
b.x = 2;//this will fail because module 'b' is loaded before 'a' so it doesn't work
});发布于 2013-03-16 11:59:29
正如您所说的,由于a.js导出一个名为a的全局变量,所以可以配置RequireJS以使用shim配置选项的方式公开它。任何需要a.js的模块都不知道它不是一个合适的模块。在您的示例中,配置如下所示:
requirejs.config({
shim: {
'a.js': {
exports: 'a' // a.js defines 'window.a'
}
}
});发布于 2013-04-15 17:43:59
这是AMD装载机的标准票价。大多数情况下,不需要垫片。您的app.js源是正确的,但是您没有显示您的b.js源。由于您对b.js有控制,所以应该将其编写为一个依赖于a.js的AMD模块。
// source code for b.js
// You have to use define, not require, and the dependency on a.js must be here rather than via a nested or internal require
define(['a.js'], function(a){
// your code for b.js
});这将确保在a.js准备执行时在b.js之前加载app.js。
https://stackoverflow.com/questions/15448134
复制相似问题