I'm running into a strange error when using dynamic imports.
I've created a reproducible repository and a Sandbox (links below).
What is odd is that the Sandbox works just fine, but the code in the repo falls apart -- with the exact same code.
It's a simple npx create-react-app
with the following content:
// App.tsx
import React from 'react';
import MySuspense from './MySuspense';
export default function App() {
return <MySuspense importPath={'@material-ui/icons/DoneAll'} />;
}
// MySuspense.tsx
import React from 'react';
type TSuspense = {
importPath: string;
};
const MySuspense = React.memo(({ importPath }: TSuspense) => {
const Component = React.lazy(() => import(importPath));
return (
<React.Suspense fallback={<div />}>
<Component />
</React.Suspense>
);
});
export default MySuspense;
This throws an error,
Error: Cannot find module '@material-ui/icons/DoneAll'
I have lint running as well, and it's giving me a warning,
./src/MySuspense.tsx
Critical dependency: the request of a dependency is an expression
But if I do,
const Component = React.lazy(() => import(`${path}`));
// instead of const Component = React.lazy(() => import(path));
Then the lint warning goes away.
If I, instead of passing the path as a prop, hardcode the import path, then it works:
const MySuspense = React.memo(({ importPath }: TSuspense) => {
const Component = React.lazy(() => import('@material-ui/icons/DoneAll'));
return (
<React.Suspense fallback={<div />}>
<Component />
</React.Suspense>
);
});
But that defeats the whole purpose of dynamic imports.
The EXACT same code running in a Sandbox works just fine. I've been pulling my hair out for hours.
I've tried adding a .babelrc
as documented here, but that didn't work,
{
"presets": ["react", "esnext"],
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
What could be wrong here? I've cloned the repo onto 3 different machines and I get the same error. How is the Sandbox any different, why would the code work there? Is there something crucial in some configuration that I'm missing or am I just going crazy here?
Honestly, any help wod be appreciated at this point, I've tried everything that I could think of at this point.
Github repo
Sandbox
question from:
https://stackoverflow.com/questions/65921524/running-into-error-error-cannot-find-module-when-using-dynamic-imports-react