Open History to see the last commit
1import * as React from 'react'
2import { isModuleNotFoundError } from '@tanstack/router-core'
3import type { AsyncRouteComponent } from './route'
4β
5/**
6 * Wrap a dynamic import to create a route component that supports
7 * `.preload()` and friendly reload-on-module-missing behavior.
8 *
9 * @param importer Function returning a module promise
10 * @param exportName Named export to use (default: `default`)
11 * @returns A lazy route component compatible with TanStack Router
12 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/lazyRouteComponentFunction
13 */
14export function lazyRouteComponent<
15 T extends Record<string, any>,
16 TKey extends keyof T = 'default',
17>(
18 importer: () => Promise<T>,
19 exportName?: TKey,
20): T[TKey] extends (props: infer TProps) => any
21 ? AsyncRouteComponent<TProps>
22 : never {
23 let loadPromise: Promise<any> | undefined
24 let comp: T[TKey] | T['default']
25 let error: any
26 let reload: boolean
27β
28 const load = () => {
29 if (!loadPromise) {
30 loadPromise = importer()
31 .then((res) => {
32 loadPromise = undefined
33 comp = res[exportName ?? 'default']
34 })
35 .catch((err) => {
36 // We don't want an error thrown from preload in this case, because
37 // there's nothing we want to do about module not found during preload.
38 // Record the error, the rest is handled during the render path.
39 error = err
40 // If the load fails due to module not found, it may mean a new version of
41 // the build was deployed and the user's browser is still using an old version.
42 // If this happens, the old version in the user's browser would have an outdated
43 // URL to the lazy module.
44 // In that case, we want to attempt one window refresh to get the latest.
45 if (isModuleNotFoundError(error)) {
46 if (
47 error instanceof Error &&
48 typeof window !== 'undefined' &&
49 typeof sessionStorage !== 'undefined'
50 ) {
51 // Again, we want to reload one time on module not found error and not enter
52 // a reload loop if there is some other issue besides an old deploy.
53 // That's why we store our reload attempt in sessionStorage.
54 // Use error.message as key because it contains the module path that failed.
55 const storageKey = `tanstack_router_reload:${error.message}`
56 if (!sessionStorage.getItem(storageKey)) {
57 sessionStorage.setItem(storageKey, '1')
58 reload = true
59 }
60 }
61 }
62 })
63 }
64β
65 return loadPromise
66 }
67β
68 const lazyComp = function Lazy(props: any) {
69 // Now that we're out of preload and into actual render path,
70 if (reload) {
71 // If it was a module loading error,
72 // throw eternal suspense while we wait for window to reload
73 window.location.reload()
74 throw new Promise(() => {})
75 }
76 if (error) {
77 // Otherwise, just throw the error
78 throw error
79 }
80β
81 if (!comp) {
82 throw load()
83 }
84β
85 return React.createElement(comp, props)
86 }
87β
88 ;(lazyComp as any).preload = load
89β
90 return lazyComp as any
91}