javascript - 在 AMD 模块之前添加非 AMD 模块

标签 javascript requirejs amd

我在一个项目中使用 requirejs,并且有 2 个模块:

  • a.js:是一个非 AMD 模块,我无法触及其代码
  • b.js:是我用 define() 函数编写的 AMD 模块。它需要 a.js 才能工作。
  • app.js:是同时使用 a.jsb.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/

相关文章:

javascript - 事件上的鼠标指针位置未以 THREE.js 上的箭头提示为中心

javascript - 当 a 为负数且 b 为非整数时,为什么 Math.pow(a, b) 为 NaN?

javascript - RequireJS 和 JavaScript API

javascript - requirejs 抛出 404 试图从 karma runner 加载文件

javascript - daterangepicker 关闭父 Bootstrap 下拉列表

javascript - 有 requirejs 在加载模块时运行回调

requirejs - 异步时的行为 : false and true

javascript - 如何编写一个可以与 Node.js、RequireJS 以及没有它们一起工作的模块

javascript - 使用选项卡时调整图表高度大小

javascript - Node : node-http-proxy and harmon: rewriting the html response from the end point instead of the 302 redirected response.