Open History to see the last commit
1import * as React from 'react'
2import { isModuleNotFoundError } from '@tanstack/router-core'
3import { isServer } from '@tanstack/router-core/isServer'
4import { reactUse } from './utils'
5import type { AsyncRouteComponent } from './route'
6β
7/**
8 * Wrap a dynamic import to create a route component that supports
9 * `.preload()` and friendly reload-on-module-missing behavior.
10 *
11 * @param importer Function returning a module promise
12 * @param exportName Named export to use (default: `default`)
13 * @returns A lazy route component compatible with TanStack Router
14 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/lazyRouteComponentFunction
15 */
16export function lazyRouteComponent<
17 T extends Record<string, any>,
18 TKey extends keyof T = 'default',
19>(
20 importer: () => Promise<T>,
21 exportName?: TKey,
22): T[TKey] extends (props: infer TProps) => any
23 ? AsyncRouteComponent<TProps>
24 : never {
25 let loadPromise: Promise<any> | undefined
26 let comp: T[TKey] | T['default']
27 let error: any
28β
29 const load = () => {
30 if (!loadPromise) {
31 error = undefined
32 loadPromise = importer()
33 .then((res) => {
34 // Resolved clients have no preload work; SSR can reuse the import.
35 if (!(isServer ?? typeof window === 'undefined')) {
36 loadPromise = undefined
37 ;(lazyComp as any).preload = undefined
38 }
39 comp = res[exportName ?? 'default']
40 })
41 .catch((err) => {
42 loadPromise = undefined
43 // We don't want an error thrown from preload in this case, because
44 // there's nothing we want to do about module not found during preload.
45 // Record the error, the rest is handled during the render path.
46 error = err
47 })
48 }
49β
50 return loadPromise
51 }
52 const lazyComp = function Lazy(props: any) {
53 if (error) {
54 // A missing module can mean that a newer deployment replaced the URL.
55 // Reload only for the error that is still current at render time, so a
56 // successful retry cannot leave a stale reload request armed.
57 if (
58 isModuleNotFoundError(error) &&
59 !(isServer ?? typeof window === 'undefined') &&
60 typeof sessionStorage !== 'undefined'
61 ) {
62 const storageKey = `tanstack_router_reload:${error.message}`
63 if (!sessionStorage.getItem(storageKey)) {
64 sessionStorage.setItem(storageKey, '1')
65 window.location.reload()
66 // Suspend forever while the document reloads.
67 throw new Promise(() => {})
68 }
69 }
70 throw error
71 }
72β
73 if (!comp) {
74 if (reactUse) {
75 reactUse(load())
76 } else {
77 throw load()
78 }
79 }
80β
81 return React.createElement(comp, props)
82 }
83β
84 ;(lazyComp as any).preload = load
85β
86 return lazyComp as any
87}