Closed Nik96i closed 2 weeks ago
I think this happen because the bundler cannot detect that's it's safe to remove the call to React.lazy. Maybe this call as a side effect and removing it will break the build. I pretty sure lazy is sideEffect free, maybe an annotation could be added to the React build to help on this pattern, this is to be discussed with the React team.
I think the second option is fine, and you will probably avoid the TS issue with this:
const HomePage = lazy(() => import("./pages/Home"));
const PageA = IS_DEV ? lazy(() => import("./pages/PageA.tsx")) : undefined;
const routes: RouteObject[] = [
{
path: "/",
element: <HomePage />
},
...( PageA ? [
{
path: "/page-a",
element: <PageA />
}
] : [] ),
]
(I just found out that the new TS config is broken in stackblitz, so I'm not 100% sure)
OK. Thank you sir. I use your solution and it works fine.
Nice!
Describe the bug
Hi. I have some react-router lazy routes and it works fine. now I want some of my routes not to be built based on some conditions. My app has two different modes and every mode has different routes. In a simple example for Page A, I don't want to be in build time. Here is my App.tsx codes.
When I build this. PageA is in the final build files:![Screenshot 2024-06-13 170731](https://github.com/vitejs/vite-plugin-react/assets/38504742/fafd1f4f-cf7d-4f37-a8dc-d53049927555)
Here are the codes in the main JS file (index-DbQkpaEw.js):
It seems PageA doesn't have any variables or something. It's also not used across the app. Why does it exist in the final build and the main JS file?
To fix this issue I have to load PageA like this:
But it gives a TypeScript error when I want to use it:
What is the right way to make lazy imports conditional and not to build them at all?
Reproduction
https://stackblitz.com/edit/vitejs-vite-pqgvpe?file=src%2Fmain.tsx
Steps to reproduce
npm install and npm run build
System Info
Used Package Manager
yarn
Logs
No response
Validations