Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  20] [ 2]  / answers: 1 / hits: 6595  / 5 Years ago, sat, october 12, 2019, 12:00:00

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.


More From » reactjs

 Answers
0

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

[#5965] Wednesday, October 9, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaceyr

Total Points: 510
Total Questions: 97
Total Answers: 116

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;