react dynamic import using a variable doesn't work

Viewed 5103

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.

1 Answers

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