Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

javascript - react dynamic import using a variable doesn't work

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...