As per webpack documentation.
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.
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.
So the below snippet works
import("./components/About").then(component => {
console.log(component, "loaded successfully");
});
The below snippet doesn't work
let a = "./components/About";
import(a).then(component => {
console.log(component, "loaded successfully");
});
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.
The above code is transpiled to
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");
});
And this gets transpiled to
let a = "./components/About";
__webpack_require__("./src lazy recursive ^.*$")("".concat(a)).then(component => {
console.log(component, "loaded successfully");
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…