我在一个项目中使用 requirejs,并且有 2 个模块:
- a.js:是一个非 AMD 模块,我无法触及其代码
- b.js:是我用
define()
函数编写的 AMD 模块。它需要a.js
才能工作。 - app.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
});
最佳答案
正如您所说,由于 a.js
导出了一个名为 a
的全局变量,因此您可以配置 RequireJS
以在 AMD 中公开它使用 shim config option 的方式。任何需要 a.js
的模块甚至不会知道它不是一个正确的模块。在你的情况下,配置将是这样的:
requirejs.config({
shim: {
'a.js': {
exports: 'a' // a.js defines 'window.a'
}
}
});
关于javascript - 在 AMD 模块之前添加非 AMD 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15448134/