File based routing lazy-loading: when new build is pushed, lazy loaded scripts fail to load and causes an error
Describe the bug
Related to https://github.com/TanStack/router/issues/1077.
The fix for https://github.com/TanStack/router/issues/1077 was on the lazyRouteComponent. The docs for the lazyRouteComponent state that:
🧠If you are using file-based routing, it's recommended to use the createLazyFileRoute function instead.
When using the createLazyFileRoute function, the bug described in 1077 still exists.
Your Example Website or App
n/a
Steps to Reproduce the Bug or Issue
Deploy a lazily loaded route built via Vite using file based routing and the createLazyFileRoute function Open the webpage root route Change something in the JS, redeploy Now try to load a lazy route, and the JS script will fail to load
Expected behavior
On 404 from the js script load, a refresh should occur like in https://github.com/TanStack/router/issues/1077.
Screenshots or Videos
No response
Platform
All browsers
Additional context
No response
@ajoslin is this something you can contribute?
I had same issue with latest version 1.19.x and I switched back to version 1.17.4, it works properly.
what worked for me was updating @tanstack/router-vite-plugin from 1.19.3 to 1.19.2. otherwise, i was getting AboutLazyImport not defined when following the Quick Start guide on a fresh build.
@thunderousNinja I think you are talking about a different issue here
It looks like Vite has a work around for this. https://vitejs.dev/guide/build.html#load-error-handling
I added a event listener
window.addEventListener('vite:preloadError', () => {
window.location.reload()
})
And in my ErrorComponent, I filter out the import error so I don't display the error message
const isModuleNotFoundError = (error: any): boolean => typeof error?.message === 'string' && /Failed to fetch dynamically imported module/.test(error.message)
export const ErrorComponent = ({ error }: { error: any }) => {
if (isModuleNotFoundError(error)) {
return <div />
}
return (
<div>
<p>Something went wrong!</p>
</div>
)
}
I'm too facing this issue. Whenever new build is deployed the routing breaks up until the page is refreshed. Where to put the window.addEventListener and the ErrorComponent?
@omairnabiel
I put the window.addEventListener in my app component file that is passed into root.render
app.tsx file:
// reloads the app if there is an error fetching an outdated chunk due to a new build deployed
window.addEventListener('vite:preloadError', () => {
window.location.reload()
})
export const App = () => ( ....
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App />)
The error component, I put in the default error component, but if you have other error components on the route level, then you may need to handle the error there too
const router = createRouter({
routeTree,
defaultErrorComponent: ErrorComponent,
})
Going to close this issue since it is more a vite issue than tanstack router issue