使用RequireJS从数组动态加载模块
Dynamic loading of modules from array using RequireJS
我正在使用RequireJS AMD加载方法开发一个应用程序。
我把我的模块动态地从配置文件中提取到阵列中
var amd_modules = ["module1", "module2","module3"]
现在我有了我需要的JS代码
require(amd_modules, function(result) {
console.log("All modules loaded");
}
现在,结果变量显示第一个模块,即"module1"。如何将其他模块也放入function()括号内的变量中。
例如
require(amd_modules, function(module1, module2, module3) { //
}
我不能写上面的硬编码,因为直到运行时才知道动态变量的数量。请告诉我如何在函数中动态捕捉对象。
Thx
只需使用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
});
然而,除非你有充分的理由这样做,否则你可能需要重新思考你设计应用程序的方式——即使在最高层,你的模块也应该简单且可测试。依赖项的数量变化很大,这表明您可能试图在回调函数中做很多事情。将每个代码路径分解为自己的模块,然后只切换到顶级依赖项。代码中:
// 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).
});
试试这样的东西:
define(function () {
var ClassLoader = function () {
var _construct = function () {
return _public;
},
_loadClass = function (className, callback) {
//
require([className],
function (LoadedClass) {
callback(LoadedClass);
});
},
_public = {
loadClass: _loadClass
};
return _construct();
}
return ClassLoader;
});
相关文章:
- 使用RequireJS从数组动态加载模块
- NgRoute未加载(模块错误)
- 动态加载模块角度
- RequireJS - 动态加载模块
- 无法在 Angular JS 中加载模块
- 从视图调用异步加载模块函数
- 主干木偶:木偶.应用程序导致 Require.js 模块加载错误,“'错误:尚未为上下文加载模块名称'A
- Webpack - 在不创建别名的情况下加载模块
- Jasmine 由于 ES6 语法而未加载模块
- 角度AMD加载模块不起作用
- 带有 angularjs 和 requirejs 的延迟加载模块
- RequireJS 有时不加载模块
- Require.js甚至在IF语句中也在加载模块
- AngularJS加载模块失败
- 节点未从项目根目录加载模块
- 通过requirejs自动加载模块
- 在运行时重新加载模块
- 动态命名的局部变量,用于加载模块
- RequireJS-加载模块的多个实例
- 无法在HotTowel SPA上加载模块