I’m having an issue with dynamic imports in a frontend app.
We have multiple instances of the app with slightly different settings and compilations. The thing is, I try to avoid if elses
and switch cases
here and dynamic imports are a really nice and clean solution for our requirements, in my opinion. But in some cases it breaks the whole app.
Our most important tech stack: react, typescript, vite
When I use multiple dynamic imports in our FE app, I end up with a blank page that shows only the default HTML from the source index.html with no JS code loaded. There are no informational, warning, or error logs in the browser’s dev-tools console. So it’s hard for me to debug this issue.
Interestingly, this problem occurs only in the production mode, not in the dev mode. In dev mode, the app works fine.
It also fails only on some specific dynamically imported modules (in the example below, it would be settings). If I remove some (actually needed) dynamically imported TypeScript modules (settings), the app works fine.
Here are examples of the code structure:
// MyComponent.tsx
import { basics } from './basics';
function MyComponent() {
return (
<div>
{`Some basics: ${basics.join(', ')}`}
<ChildComponent />
</div>
);
}
// basics/index.ts
const { appId } = getConfig();
export const basics = import(`./basics.${appId}.ts`).catch(() => import('./basics.default'));
// Child.tsx
const { appId } = getConfig();
const Child = lazy(() => import(`./ChildComponent.${appId}.tsx`).catch(() => import('./ChildComponent.default')));
export default (props: ChildComponentProps) => {
return (
<Suspense>
<Child {...props} />
</Suspense>
);
};
// Child.tsx
import { settings } from './settings';
function Child() {
return (
<div>
{`Hello ${settings.appName}`}
</div>
);
}
// settings/index.ts
const { appId } = getConfig();
export const settings = import(`./settings.${appId}.ts`).catch(() => import('./settings.default'));
The dynamic import of React components via lazy and ES modules like ‘basics’ are not the problem, but the TypeScript modules like ‘settings’. So I’m confused here and I hope someone can explain me this behavior.