Home > Back-end >  ReactJS string variable cannot be used within an import(), but the same string hardcoded works?
ReactJS string variable cannot be used within an import(), but the same string hardcoded works?

Time:08-11

I'm running into something quite basic.

const mdLoc = "../markdowns/doc.md";
useEffect(() => {
    import(mdLoc) // yields error: Cannot find module location

but hardcoding the string works perfectly:

useEffect(() => {
    import("../markdowns/doc.md") // yields a successful import

What am I missing?

CodePudding user response:

As far as I'm aware, Webpack doesn't allow you to use a dynamic value (variable) in an import()

https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

Dynamic expressions in import() 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. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included.

It is able to resolve an expression and and resolve all variants as a single dependent chunk to import as in the example linked:

const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then((module) => {
  // do something with the translations
});

Huge warning: this import will resolve all variations into one chunk which I think is unintuitive.

For example, import(./locale/${language}.json) will cause every .json file in the ./locale directory to be bundled into the new chunk.

I think one thing to remember is that the dynamic import() feature is merely function-like, and your usual considerations about function arguments and signatures do not necessarily apply to this syntax.

Just like how import React from "react" has specific requirements (you cannot use a variable in place of "react"), so does import() -- it is not a normal function.

  • Related