使用变量反应动态导入不起作用 [英] react dynamic import using a variable doesn't work
问题描述
使用React,谁能解释我为什么使用变量时动态导入失败?
With React, can anyone explain me why the dynamic import fail when we use a variable ?
// Do not work
let module = "./DynamicComponent";
import(module).then(ModuleLoaded => {})
// Works
import("./DynamicComponent").then(ModuleLoaded => {})
我尝试刷新浏览器缓存,但没有任何变化.
I tried to refresh the browser cache but nothing change.
推荐答案
根据webpack文档.
As per webpack documentation.
不可能使用完全动态的import语句,例如import(foo).因为foo可能是任何文件中的任何路径您的系统或项目.
It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.
import()必须至少包含有关以下内容的信息:模块已找到.
The import() must contain at least some information about where the module is located.
https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import .
因此以下代码段有效.
import("./components/About").then(component => {
console.log(component, "loaded successfully");
});
以下代码段无效.
let a = "./components/About";
import(a).then(component => {
console.log(component, "loaded successfully");
});
我在任何地方都找不到找到确切原因的解释,即上述代码为何起作用.但是我的直觉是webpack不知道变量 a
的数据类型(必须是字符串),因此无法在动态导入中使用它.
I can't find an explanation anywhere that states the exact reason, why the above code works. But my intuition is webpack is not aware of the data type of variable a
(It has to be a string) hence not able to use it in a dynamic import.
上面的代码被翻译为
let a = "./components/About";
__webpack_require__("./src lazy recursive")(a).then(component => {
console.log(component, "loaded successfully");
});
下面的代码实际上有效(将变量包含在字符串文字中).
The below code actually works(Embedding the variable inside a string literal)..
let a = "./components/About";
import(`${a}`).then(component => {
console.log(component, "loaded successfully");
});
这被翻译成.
let a = "./components/About";
__webpack_require__("./src lazy recursive ^.*$")("".concat(a)).then(component => {
console.log(component, "loaded successfully");
});
这篇关于使用变量反应动态导入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!