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

Add non-AMD modules before AMD modules

本文关键字:AMD 模块 添加      更新时间:2023-09-26

我正在使用一个项目的要求,我有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
});

现在的问题是:app.jsrequire()两个模块的最简单方法是什么?我不能这样做:

//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以使用shim配置选项以AMD方式公开它。任何需要a.js的模块甚至不知道它不是一个合适的模块。在您的情况下,配置将是这样的:

requirejs.config({
    shim: {
        'a.js': {
            exports: 'a' // a.js defines 'window.a'
        }
    }
});

这是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
});

这将确保在app.js准备执行时a.js在b.js之前被加载。