Open History to see the last commit
1import * as React from 'react'
2import { Outlet } from './Match'
3import type { AsyncRouteComponent } from './route'
4β
5// If the load fails due to module not found, it may mean a new version of
6// the build was deployed and the user's browser is still using an old version.
7// If this happens, the old version in the user's browser would have an outdated
8// URL to the lazy module.
9// In that case, we want to attempt one window refresh to get the latest.
10function isModuleNotFoundError(error: any): boolean {
11 // chrome: "Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
12 // firefox: "error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
13 // safari: "Importing a module script failed."
14 if (typeof error?.message !== 'string') return false
15 return (
16 error.message.startsWith('Failed to fetch dynamically imported module') ||
17 error.message.startsWith('error loading dynamically imported module') ||
18 error.message.startsWith('Importing a module script failed')
19 )
20}
21β
22export function ClientOnly({
23 children,
24 fallback = null,
25}: React.PropsWithChildren<{ fallback?: React.ReactNode }>) {
26 return useHydrated() ? <>{children}</> : <>{fallback}</>
27}
28β
29function subscribe() {
30 return () => {}
31}
32β
33export function useHydrated() {
34 return React.useSyncExternalStore(
35 subscribe,
36 () => true,
37 () => false,
38 )
39}
40β
41export function lazyRouteComponent<
42 T extends Record<string, any>,
43 TKey extends keyof T = 'default',
44>(
45 importer: () => Promise<T>,
46 exportName?: TKey,
47 ssr?: () => boolean,
48): T[TKey] extends (props: infer TProps) => any
49 ? AsyncRouteComponent<TProps>
50 : never {
51 let loadPromise: Promise<any> | undefined
52 let comp: T[TKey] | T['default']
53 let error: any
54 let reload: boolean
55β
56 const load = () => {
57 if (typeof document === 'undefined' && ssr?.() === false) {
58 comp = (() => null) as any
59 return Promise.resolve()
60 }
61 if (!loadPromise) {
62 loadPromise = importer()
63 .then((res) => {
64 loadPromise = undefined
65 comp = res[exportName ?? 'default']
66 })
67 .catch((err) => {
68 // We don't want an error thrown from preload in this case, because
69 // there's nothing we want to do about module not found during preload.
70 // Record the error, the rest is handled during the render path.
71 error = err
72 if (isModuleNotFoundError(error)) {
73 if (
74 error instanceof Error &&
75 typeof window !== 'undefined' &&
76 typeof sessionStorage !== 'undefined'
77 ) {
78 // Again, we want to reload one time on module not found error and not enter
79 // a reload loop if there is some other issue besides an old deploy.
80 // That's why we store our reload attempt in sessionStorage.
81 // Use error.message as key because it contains the module path that failed.
82 const storageKey = `tanstack_router_reload:${error.message}`
83 if (!sessionStorage.getItem(storageKey)) {
84 sessionStorage.setItem(storageKey, '1')
85 reload = true
86 }
87 }
88 }
89 })
90 }
91β
92 return loadPromise
93 }
94β
95 const lazyComp = function Lazy(props: any) {
96 // Now that we're out of preload and into actual render path,
97 if (reload) {
98 // If it was a module loading error,
99 // throw eternal suspense while we wait for window to reload
100 window.location.reload()
101 throw new Promise(() => {})
102 }
103 if (error) {
104 // Otherwise, just throw the error
105 throw error
106 }
107β
108 if (!comp) {
109 throw load()
110 }
111β
112 if (ssr?.() === false) {
113 return (
114 <ClientOnly fallback={<Outlet />}>
115 {React.createElement(comp, props)}
116 </ClientOnly>
117 )
118 }
119 return React.createElement(comp, props)
120 }
121β
122 ;(lazyComp as any).preload = load
123β
124 return lazyComp as any
125}