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