I’m having an issue with my React project using code splitting.
For reference I’m using:
- React 18.2.0
- Vite 5.2.0
I need to load some components dynamically based on some redux state. It’s working on local but its failing on prod.
To understand how its working, this loads on a certain route, lets say ‘/sample’ and from the left hand side you select a question and its loaded onto the container (The click sets the state on redux that its used on this component), based on the import route, the react router routes are not affected by this import.
const LoadedQuestion = useMemo(() => {
let importPath = '';
const questionAvailableIn = question?.availableIn
? getQuestionnaireTypeName(Math.min(...question?.availableIn))
: undefined;
if (questionAvailableIn) {
importPath = `../../../components/Questions/${questionnaireType}/${loadedQuestionComponent?.section}/${loadedQuestionComponent?.question}/index.tsx`;
} else {
importPath = `../../../components/Questions/${loadedQuestionComponent?.section}/${loadedQuestionComponent?.question}/index.tsx`;
}
return loadedQuestionComponent?.section
? React.lazy(() => import(/* @vite-ignore */ importPath))
: React.lazy(
() =>
import(
/* @vite-ignore */ `../../../components/Questions/Default.tsx`
)
);
}, [loadedQuestionComponent, questionnaireType]);
I’m using React.lazy to import as you see based on some variables from redux state. this is the render
return (
<div className={`flex justify-center h-full ${styles.container}`}>
<div>
<Suspense fallback={<div></div>}>
<div className={`${styles.fontCustom} p-20`}>
<Fade>
<LoadedQuestion question={question ? question : {}} />
</Fade>
</div>
</Suspense>
</div>
</div>
);
When I run this on local it works great but it fails on prod somehow returning the failed to fetch dynamically error.
This is my vite.config file:
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import tsconfigPaths from 'vite-tsconfig-paths';
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
define: {
'process.env.REACT_APP_BASE_URL_FIREBASE': JSON.stringify(
env.REACT_APP_BASE_URL_FIREBASE
),
},
plugins: [react(), tsconfigPaths()],
root: 'src',
build: {
outDir: '../dist',
},
resolve: {
alias: {
'@': path.resolve(__dirname, './'),
},
},
};
});
Any ideas?? I already saw some SO threads on this, I tried the solutions but still nothing. Thanks in advance.
I cannot use static import, I know that it would probably solve the issue but its not viable, I need to code split.
I also tried the @ defined in the alias for vite. Works great for importing assets like svg, somehow with React.lazy and import its not working.
I also tried to re import with retries but still unsucessful.
import React from 'react';
export const lazyWithRetries: typeof React.lazy = (importer) => {
const retryImport = async () => {
try {
return await importer();
} catch (error: any) {
for (let i = 0; i < 5; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** i));
const url = new URL(
error.message
.replace('Failed to fetch dynamically imported module: ', '')
.trim()
);
url.searchParams.set('t', `${+new Date()}`);
try {
return await import(url.href);
} catch (e) {
console.log('retrying import');
}
}
throw error;
}
};
return React.lazy(retryImport);
};