3

I faced with a weird problem while using reactjs dynamic import. Let's say I have a component which it's name is ComponentA and it's path is like myComponents/ComponentA. Now when I dynamically import it like the following code, it would work well:

Promise.all(
        [
            import('myComponents/ComponentA'),
            // other imports
        ]
    ).then(....);

But if I define my component path in a constant variable like the following :

//before definition of my current component
const PATH = 'myComponents/ComponentA';
.
.
.
// some where in my component class
Promise.all(
    [
        import(PATH),
        // other imports
    ]
).then(....);

it would give me an error like this:

Error: Cannot find module 'myComponents/ComponentA'.

And some times if I just add an empty string to my PATH variable would solve the problem and some times it doesn't.

//before definition of my current component
const PATH = 'myComponents/ComponentA';
.
.
.
// some where in my component class
Promise.all(
    [
       import(''+PATH), // some times by adding empty string, problem would be solved
       // other imports
    ]
 ).then(....);

any idea about what is going on would be appreciated.

3
  • Make the module path relative. Commented Apr 5, 2019 at 19:26
  • Have you managed to figure out a way around this? Commented Jan 28, 2021 at 6:28
  • @MikeK, it's for a long ago and I didn't found a solution for it. As I remember I found a way to achieve my main goal. Unfortunately because it is for a long time a go and now a day I am working with vuejs, I don't remember anything a bout it :(. Commented Jan 28, 2021 at 10:03

2 Answers 2

1

Maybe try this new ES6 syntax:

const PATH = 'myComponents/ComponentA';
Promise.all(
    [
       import(`${PATH}`), // try pass it like this
       // other imports
    ]
 ).then(....);
Sign up to request clarification or add additional context in comments.

2 Comments

did you try the backticks ? we can try it with space like this import(' ${PATH}') (backticks around ${PATH} cant do that in a comment)
Sorry for my late respond, but this didn't work too :(.
1

You have at least to have an initial literal folder string (no variable) to restrict what modules can be loaded, because it will bundle all possible files.

This is a limit of webpack. For details see https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

It is truly a pity it doesn't recognize the const other than literals.

Comments

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.