使用RequireJS从数组动态加载模块

use*_*539 12 javascript requirejs

我正在使用RequireJS AMD加载方法处理应用程序.

我将我的模块动态地从配置文件中拾取到数组中

var amd_modules = ["module1", "module2","module3"]
Run Code Online (Sandbox Code Playgroud)

现在我有了requireJS代码

require(amd_modules, function(result) {
console.log("All modules loaded");
}
Run Code Online (Sandbox Code Playgroud)

现在,结果变量显示第一个模块"module1".如何将其他模块也放入function()括号内的变量中.

例如,

require(amd_modules, function(module1, module2, module3) { //
}
Run Code Online (Sandbox Code Playgroud)

我无法编写上述硬编码,因为直到运行时才知道动态变量的数量.请告诉我如何在函数内动态捕获对象.

谢谢

Sea*_*ira 13

只需使用arguments:

require(amd_modules, function() {
    console.log("All modules loaded");
    // arguments should now be an array of your required modules
    // in the same order you required them
});
Run Code Online (Sandbox Code Playgroud)

但是,除非您有充分的理由这样做,否则您可能希望重新考虑设计应用程序的方式 - 即使在最高级别,您的模块也应该简单且可测试.拥有大量不同的依赖关系表明您可能正在尝试在回调函数中做很多事情.将每个代码路径分解为自己的模块,然后仅切换到顶级依赖项.在代码中:

// Instead of this:
require(amd_modules, function() {
    console.log("All modules loaded");
    if (complex_condition_A) {
        var x = arguments[0],
                y = arguments[1],
                z = arguments[2];
        // Do things with x, y and z
    }
    else if (complex_condition_B) {
        var a = arguments[0],
                b = arguments[1];
        // Do things with a and b
    }
    else {
        // et cetera, et cetera, et cetera
    }
});


// Do this instead
var rootModule;
if (complex_condition_A) rootModule = "A";
else if (complex_condition_B) rootModule = "B";
else rootModule = "C";
require(rootModule, function(root) {
    // Root has the same API, regardless of which implementation it is
    // This might be as simple as an `init` method that does everything
    // or as complex as, say Facebook's API, but with different libraries
    // loaded depending on the platform the page is loaded on
    // (IE vs. Android for example).
});
Run Code Online (Sandbox Code Playgroud)