gpt4 book ai didi

javascript - 使用变量 react 动态导入不起作用

转载 作者:行者123 更新时间:2023-12-01 00:33:02 30 4
gpt4 key购买 nike

使用 React,谁能解释一下为什么当我们使用变量时动态导入会失败?

// Do not work
let module = "./DynamicComponent";
import(module).then(ModuleLoaded => {})
// Works
import("./DynamicComponent").then(ModuleLoaded => {})

我尝试刷新浏览器缓存,但没有任何变化。

最佳答案

根据webpack文档。

It is not possible to use a fully dynamic import statement, such asimport(foo). Because foo could potentially be any path to any file inyour system or project.

The import() must contain at least some information about where themodule 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 的数据类型(它必须是字符串),因此无法在动态导入中使用它。

上面的代码被转译为

let a = "./components/About";
__webpack_require__("./src lazy recursive")(a).then(component => {
console.log(component, "loaded successfully");
});

下面的代码实际上有效(将变量嵌入字符串文字中)..

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");
});

关于javascript - 使用变量 react 动态导入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349959/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com