7

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.

2
  • You using CRA Or your custom webpack config? Seems fine to me and it should work. Its JS and nothing seems related to React based on the code you posted. Commented Oct 12, 2019 at 1:03
  • I am using the webpack-dev-server by the react-scripts start from create-react-app utils Commented Oct 12, 2019 at 1:09

1 Answer 1

12

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");
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @nithin. I would have never thinking about embedding the variable.
Embedding the variable inside a string literal does not work for me. Is there anything else I have to take care of?
Same for me, even if I embed the variable it is not working. I am using a React framework.
Where does "lazy recursive" comes from and why is it related to this discussion?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.