Production Build with React.lazy: Failed to fetch dynamically imported module #2682
-
Hey!
Here's some simplified code from the router file: import React, { Component, Suspense, lazy } from "react";
import history from "../history-helper";
import { Router, Switch, Route } from "react-router-dom";
const HomeView = lazy(() => import("@views/home"));
const ShoppingCartView = lazy(() => import("@views/shoppingcart"));
class Routes extends Component {
render() {
return (
<Router history={history}>
<div style={{ minHeight: "75vh" }}>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route component={ShoppingCartView} path="/shopping-cart" />
<Route component={HomeView} path="/" />
</Switch>
</Suspense>
</div>
</Router>
);
}
}
export default Routes; Here's my config/vite.config.ts: import reactRefresh from "@vitejs/plugin-react-refresh";
import path from 'path';
import {defineConfig} from "vite";
import {getAliases} from "vite-aliases";
const aliases = getAliases();
export default defineConfig({
root : path.resolve(__dirname, "../"),
publicDir : path.resolve(__dirname, "../public"),
plugins : [ reactRefresh() ],
resolve : {
alias : aliases,
},
build : {
emptyOutDir : true,
outDir : path.resolve(__dirname, '../build')
},
server : {proxy : {'/api' : 'http://localhost:5000'}}
}); Any idea what the problem might be? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Found out that the issue was with none of the code above. In one of my components, I was dynamically importing some css in a useEffect hook and Vite preload didn't seem to like it with:
I replaced it with a static import and it worked fine. |
Beta Was this translation helpful? Give feedback.
-
Maybe It works in my project, just like below: import { lazy, Suspense } from 'react'
const modules = import.meta.glob('../pages/**/index.tsx')
export function LazyImportComponent(action: any, loading?: React.ReactNode) {
const LazyComponent = lazy(action)
return (props: Record<string, any>) => {
return (
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent {...props} />
</Suspense>
)
}
}
// path like '../pages/myModule/index.tsx'
export default function lazyImport(path: string, props: Record<string, any> = {}) {
const MyComponent = LazyImportComponent(modules[path])
return <MyComponent {...props} />
} |
Beta Was this translation helpful? Give feedback.
-
If someone still faces this issue, I found a solution using Vite's PWA plugin: https://vite-pwa-org.netlify.app/ Here's how I set it up:
|
Beta Was this translation helpful? Give feedback.
Found out that the issue was with none of the code above. In one of my components, I was dynamically importing some css in a useEffect hook and Vite preload didn't seem to like it with:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
I replaced it with a static import and it worked fine.