Reputation: 3439
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.
Upvotes: 3
Views: 2317
Reputation: 96
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.
Upvotes: 1
Reputation: 3374
Maybe try this new ES6 syntax:
const PATH = 'myComponents/ComponentA';
Promise.all(
[
import(`${PATH}`), // try pass it like this
// other imports
]
).then(....);
Upvotes: 1