Open History to see the last commit
1/**
2 * Route HMR keeps the previous `component` (and the other component options)
3 * so that React Refresh can patch it in place. That only works when the value
4 * is bound to a top-level name React Refresh registers. These tests compile
5 * route files with the HMR transforms, then run Vite's Oxc React Refresh
6 * transform (the one `@vitejs/plugin-react` uses) on the output to see which
7 * components are registered and how their hook signatures are computed.
8 */
9import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
10import path from 'node:path'
11import { createServer } from 'vite'
12import { describe, expect, it } from 'vitest'
13import { tanstackRouter } from '../src/vite'
14import {
15 compileRouteModules,
16 declarationOf,
17 declaratorName,
18 evaluateModule,
19 expectRefreshableRouteOption,
20 expectRegisteredRouteOption,
21 expectValidModules,
22 exportedBinding,
23 exportedNames,
24 getRouteOption,
25 head,
26 importedNames,
27 parseModule,
28 reactRefresh,
29 topLevelDeclarators,
30 transformWithRouteHmrPlugin,
31} from './regression-helpers'
32import type { ESTree, ViteDevServer } from 'vite'
33β
34/** Compiles every module the code splitter emits, with React HMR. */
35function compileWithCodeSplitting(code: string) {
36 return compileRouteModules(code, { hmr: true }).modules
37}
38β
39describe('React Refresh registers route components', () => {
40 // Source: React Refresh ReactFreshBabelPlugin-test "registers top-level
41 // variable declarations with function expressions" and "... with arrow functions"
42 it.each([
43 ['an arrow function', `() => <p>hi</p>`],
44 ['an anonymous function expression', `function () { return <p>hi</p> }`],
45 ['a parenthesized arrow function', `(() => <p>hi</p>)`],
46 ])('written inline as %s', async (_, component) => {
47 const code = transformWithRouteHmrPlugin(
48 `${head}export const Route = createFileRoute('/')({ component: ${component} })`,
49 )
50 await expectRegisteredRouteOption(code, 'component')
51 })
52β
53 // Source: ReactFreshBabelPlugin-test "registers top-level variable
54 // declarations with arrow functions"
55 it.each([
56 ['as any', `(() => <p>hi</p>) as any`],
57 ['satisfies', `(() => <p>hi</p>) satisfies FC`],
58 ['a non-null assertion', `(() => <p>hi</p>)!`],
59 ])('written inline and wrapped in %s', async (_, component) => {
60 const code = transformWithRouteHmrPlugin(
61 `${head}import type { FC } from 'react'
62export const Route = createFileRoute('/')({ component: ${component} })`,
63 )
64 await expectRegisteredRouteOption(code, 'component')
65 })
66β
67 it('for every inline component option of a root route, under distinct names', async () => {
68 const options = {
69 component: '() => <p>component</p>',
70 pendingComponent: '() => <p>pending</p>',
71 errorComponent: '({ error }) => <p>{String(error)}</p>',
72 notFoundComponent: '() => <p>not found</p>',
73 shellComponent: '({ children }) => <html><body>{children}</body></html>',
74 }
75 const { reference } = compileWithCodeSplitting(
76 `import { createRootRoute } from '@tanstack/react-router'
77export const Route = createRootRoute({
78${Object.entries(options)
79 .map(([key, value]) => ` ${key}: ${value},`)
80 .join('\n')}
81})`,
82 )
83 const bindings = new Set<string>()
84 for (const option of Object.keys(options)) {
85 bindings.add(await expectRegisteredRouteOption(reference!, option))
86 }
87 expect(bindings.size).toBe(Object.keys(options).length)
88 })
89β
90 // Source: ReactFreshBabelPlugin-test "only registers pascal case functions"
91 // and "uses original function declaration if it get reassigned"
92 it.each([
93 ['a const arrow function', `const page = () => <p>hi</p>`],
94 [
95 'a function expression that names itself',
96 `const page = function page() { return <p>{typeof page}</p> }`,
97 ],
98 [
99 'a reassigned function declaration',
100 `import { connect } from './connect'\nfunction page() { return <p>hi</p> }\npage = connect(page)`,
101 ],
102 ])('declared lowercase as %s, by renaming it', async (_, declaration) => {
103 const code = transformWithRouteHmrPlugin(
104 `${head}${declaration}\nexport const Route = createFileRoute('/')({ component: page })`,
105 )
106 const binding = await expectRegisteredRouteOption(code, 'component')
107 expect(binding).toMatch(/^[A-Z]/)
108 })
109β
110 // Source: ReactFreshBabelPlugin-test "registers top-level exported function
111 // declarations" and "registers top-level exported named arrow functions"
112 it.each([
113 ['export function page', `export function page() { return <p>hi</p> }`],
114 ['export { page }', `const page = () => <p>hi</p>\nexport { page }`],
115 [
116 'export default page',
117 `function page() { return <p>hi</p> }\nexport default page`,
118 ],
119 ])(
120 'renamed lowercase and exported (%s), keeping the exports',
121 async (_, declaration) => {
122 const source = `${head}${declaration}\nexport const Route = createFileRoute('/')({ component: page })`
123 const code = transformWithRouteHmrPlugin(source)
124 await expectRegisteredRouteOption(code, 'component')
125 expect(exportedNames(code)).toEqual(
126 expect.arrayContaining(exportedNames(source)),
127 )
128 },
129 )
130β
131 // React Refresh resolves memo(...) through the function it wraps.
132 it('wrapped in memo(...) around a top-level component', async () => {
133 await expectRefreshableRouteOption(
134 transformWithRouteHmrPlugin(`${head}import { memo } from 'react'
135function Page() {
136 return <p>hi</p>
137}
138export const Route = createFileRoute('/')({ component: memo(Page) })`),
139 'component',
140 )
141 })
142β
143 // Source: ReactFreshBabelPlugin-test "does not consider require-like methods to be HOCs"
144 it('but leaves an imported lowercase component to the module that declares it', () => {
145 const code = transformWithRouteHmrPlugin(
146 `${head}import { page } from './page'
147export const Route = createFileRoute('/')({ component: page })`,
148 )
149 const { value } = getRouteOption(parseModule(code), 'component')
150 expect((value as ESTree.IdentifierReference).name).toBe('page')
151 expect(importedNames(code, './page')).toEqual(['page'])
152 })
153β
154 // Source: ReactFreshBabelPlugin-test "registers top-level function declarations"
155 it('renames only the component binding, not an inner binding with its name', async () => {
156 const code = transformWithRouteHmrPlugin(
157 `${head}function page() {
158 const page = 'inner-marker'
159 return <p>{page}</p>
160}
161export const Route = createFileRoute('/')({ component: page })`,
162 )
163 await expectRegisteredRouteOption(code, 'component')
164 const { Route } = await evaluateModule(code, {
165 '@tanstack/react-router': {
166 createFileRoute: () => (options: unknown) => ({ options }),
167 },
168 })
169 expect((Route as any).options.component()).toBe('<p>inner-marker</p>')
170 })
171β
172 // Source: ReactFreshIntegration-test "preserves state ..." (families are
173 // matched by registration name)
174 it('names hoisted components after their option, so adding options keeps the family', async () => {
175 const before = transformWithRouteHmrPlugin(
176 `${head}export const Route = createFileRoute('/')({ component: () => <p>v1</p> })`,
177 )
178 const after = transformWithRouteHmrPlugin(
179 `${head}export const Route = createFileRoute('/')({
180 pendingComponent: () => <p>pending</p>,
181 errorComponent: () => <p>error</p>,
182 component: () => <p>v2</p>,
183})`,
184 )
185 expect(await expectRegisteredRouteOption(after, 'component')).toBe(
186 await expectRegisteredRouteOption(before, 'component'),
187 )
188 })
189β
190 // Source: ReactFreshBabelPlugin-test "includes custom hooks into the signatures"
191 it('with the hook signature of the component the user wrote, also in the split chunk', async () => {
192 const declarations = `import { useState } from 'react'
193const format = (n: number) => String(n)
194function useCounter() {
195 const [count] = useState(0)
196 return format(count)
197}`
198 const component = `() => {
199 const count = useCounter()
200 return <p>{count}</p>
201}`
202 const { signatures } = await reactRefresh(
203 `${declarations}\nconst Page = ${component}\nexport const Route = {}`,
204 )
205 const expected = signatures.get('Page')
206 expect(expected).toBeDefined()
207 // The loader shares `format` with the component's hook.
208 const source = `${head}${declarations}
209export const Route = createFileRoute('/')({
210 loader: () => format(1),
211 component: ${component},
212})`
213β
214 const hmr = transformWithRouteHmrPlugin(source)
215 const hoisted = await expectRegisteredRouteOption(hmr, 'component')
216 expect((await reactRefresh(hmr)).signatures.get(hoisted)).toBe(expected)
217β
218 const modules = compileWithCodeSplitting(source)
219 expect(modules.shared).toMatch(declarationOf('format'))
220 const chunkSignatures = (await reactRefresh(modules['virtual component']!))
221 .signatures
222 expect([...chunkSignatures.values()]).toContain(expected)
223 })
224})
225β
226describe('React Refresh registers split route components', () => {
227 /** The binding a chunk exports as `component`, and what React Refresh registers. */
228 async function splitComponent(chunk: string) {
229 const binding = exportedBinding(chunk, 'component')
230 expect(binding).toBeDefined()
231 return {
232 binding: binding!,
233 registered: (await reactRefresh(chunk)).registered,
234 }
235 }
236β
237 // Source: ReactFreshBabelPlugin-test "registers likely HOCs with inline functions"
238 it.each([
239 ['memo', `import { memo } from 'react'`, `memo(() => <p>hi</p>)`],
240 [
241 'forwardRef',
242 `import { forwardRef } from 'react'`,
243 `forwardRef(function (props, ref) {\n return <p ref={ref}>hi</p>\n})`,
244 ],
245 ])(
246 'written inline in a %s call, with the function it wraps',
247 async (hoc, imports, component) => {
248 const modules = compileWithCodeSplitting(`${head}${imports}
249export const Route = createFileRoute('/')({ component: ${component} })`)
250 await expectValidModules(modules)
251 const { binding, registered } = await splitComponent(
252 modules['virtual component']!,
253 )
254 expect(registered).toEqual(
255 expect.arrayContaining([binding, `${binding}$${hoc}`]),
256 )
257 },
258 )
259β
260 // Source: ReactFreshBabelPlugin-test "registers top-level function
261 // declarations" (one component, two uses)
262 it('that is also the unsplit pendingComponent', async () => {
263 const modules = compileWithCodeSplitting(`${head}function page() {
264 return <p>hi</p>
265}
266export const Route = createFileRoute('/')({ component: page, pendingComponent: page })`)
267 await expectValidModules(modules)
268 const { binding, registered } = await splitComponent(
269 modules['virtual component']!,
270 )
271 expect(registered).toContain(binding)
272 })
273β
274 // Source: ReactFreshBabelPlugin-test "registers top-level exported function
275 // declarations" (`export { Baz }`)
276 it('but keeps a component exported by specifier in the route module, registered and exported', async () => {
277 const modules =
278 compileWithCodeSplitting(`${head}const page = () => <p>hi</p>
279export { page }
280export const Route = createFileRoute('/')({ component: page })`)
281 await expectValidModules(modules)
282 expect(exportedNames(modules.reference!)).toContain('page')
283 await expectRegisteredRouteOption(modules.reference!, 'component')
284 })
285β
286 // Inputs adapted from React Compiler simple-alias.js: a lowercase component
287 // that the loader also uses moves to the shared module, and React HMR
288 // renames lowercase split components.
289 it('keeps the modules valid when a lowercase component is shared with the loader', async () => {
290 const modules = compileWithCodeSplitting(`${head}function page() {
291 return <div>hello</div>
292}
293function load() {
294 return page.name
295}
296export const Route = createFileRoute('/')({ component: page, loader: load })`)
297 expect(modules.shared).toMatch(declarationOf('page'))
298 await expectValidModules(modules)
299 })
300})
301β
302describe('React Refresh hoisting picks names nothing else uses', () => {
303 it.each([
304 [
305 'a top-level const',
306 `const TSRComponent = 'taken'`,
307 `<p>{TSRComponent}</p>`,
308 ],
309 ['an import', `import { TSRComponent } from './taken'`, `<TSRComponent />`],
310 [
311 'a function declared after the route',
312 ``,
313 `<p>{TSRComponent()}</p>`,
314 `\nfunction TSRComponent() { return 'taken' }`,
315 ],
316 ])('not a name held by %s', async (_, before, jsx, after = '') => {
317 const code = transformWithRouteHmrPlugin(
318 `${head}${before}
319export const Route = createFileRoute('/')({ component: () => ${jsx} })${after}`,
320 )
321 // A reused name would redeclare the user's binding (an invalid module).
322 const binding = await expectRegisteredRouteOption(code, 'component')
323 expect(binding).not.toBe('TSRComponent')
324 })
325β
326 it('nor a global the component reads', async () => {
327 const code = transformWithRouteHmrPlugin(
328 `${head}export const Route = createFileRoute('/')({
329 component: () => <p>{typeof TSRPendingComponent}</p>,
330 pendingComponent: () => <p>pending</p>,
331})`,
332 )
333 const pending = await expectRegisteredRouteOption(code, 'pendingComponent')
334 expect(pending).not.toBe('TSRPendingComponent')
335 // `TSRPendingComponent` must stay an unresolved global inside `component`.
336 expect(code).not.toMatch(declarationOf('TSRPendingComponent'))
337 })
338})
339β
340describe('React Refresh hoisting of inline route components', () => {
341 it('hoists the root route component but not the components of routes a function creates', async () => {
342 const { reference } = compileWithCodeSplitting(`
343import { createRootRoute, createRoute } from '@tanstack/react-router'
344export function makeChild(label: string) {
345 return createRoute({
346 getParentRoute: () => Route,
347 path: label,
348 component: () => <div>{label}</div>,
349 })
350}
351export const Route = createRootRoute({ component: () => <div /> })
352`)
353 const program = parseModule(reference!)
354 // `label` only exists inside `makeChild`; any other top-level statement
355 // that mentions it reads an undefined global at render time.
356 const statementsUsingLabel = program.body
357 .map((statement) => reference!.slice(statement.start, statement.end))
358 .filter(
359 (statement) =>
360 /\blabel\b/.test(statement) &&
361 !statement.includes('function makeChild('),
362 )
363 expect(statementsUsingLabel).toEqual([])
364 // React Refresh can only register components bound to top-level names.
365 await expectRegisteredRouteOption(reference!, 'component')
366 })
367β
368 it("hoists the components of the module's Route when another route is created first", async () => {
369 const code = `import { createFileRoute, createRoute } from '@tanstack/react-router'
370export const extra = createRoute({
371 getParentRoute: () => Route,
372 path: 'extra',
373 component: () => <p>extra</p>,
374})
375export const Route = createFileRoute('/')({
376 component: () => <p>home</p>,
377 pendingComponent: () => <p>pending</p>,
378})`
379 await expectRefreshableRouteOption(
380 transformWithRouteHmrPlugin(code),
381 'component',
382 )
383 // The split `component` loads from its chunk; the reference module keeps
384 // `pendingComponent`.
385 await expectRefreshableRouteOption(
386 compileWithCodeSplitting(code).reference!,
387 'pendingComponent',
388 )
389 })
390β
391 it('declares hoisted components before the route that uses them', () => {
392 // The lowercase `page`, declared in the same statement as `Route`, is
393 // renamed for React Refresh as well.
394 const { reference } = compileWithCodeSplitting(`
395import { createRootRoute } from '@tanstack/react-router'
396export const page = () => <div />, Route = createRootRoute({
397 component: page,
398 pendingComponent: () => <div />,
399})
400`)
401 const program = parseModule(reference!)
402 const { route, value } = getRouteOption(program, 'pendingComponent')
403 expect(value.type).toBe('Identifier')
404 const name = (value as ESTree.IdentifierReference).name
405 const declaration = topLevelDeclarators(program).find(
406 (declarator) => declaratorName(declarator) === name,
407 )
408 // A `const` used before its declaration throws a TDZ ReferenceError when
409 // the route is created.
410 expect(declaration).toBeDefined()
411 expect(declaration!.start).toBeLessThan(route.start)
412 })
413})
414β
415/**
416 * React HMR renames and hoists route components, and may split them out of the
417 * route module. Modules that import the route module's exports still need them,
418 * as the same values the route options use. These tests load the route module
419 * from a Vite dev server running the real plugin.
420 */
421describe.each([true, false])(
422 'route module exports with React HMR and autoCodeSplitting=%s',
423 (autoCodeSplitting) => {
424 /**
425 * Transforms and loads `routes/page.tsx` in a dev server, and passes its
426 * exports to `use` while the server can still load split chunks.
427 */
428 async function withRouteModule(
429 route: string,
430 use: (routeModule: Record<string, any>) => Promise<void> | void,
431 ) {
432 const root = await mkdtemp(path.join(__dirname, '.hmr-exports-'))
433 let server: ViteDevServer | undefined
434 try {
435 await mkdir(path.join(root, 'routes'))
436 await writeFile(
437 path.join(root, 'routes/__root.tsx'),
438 `import { createRootRoute } from '@tanstack/react-router'
439export const Route = createRootRoute({})`,
440 )
441 await writeFile(path.join(root, 'routes/page.tsx'), route)
442 server = await createServer({
443 root,
444 configFile: false,
445 logLevel: 'silent',
446 plugins: [
447 tanstackRouter({
448 target: 'react',
449 autoCodeSplitting,
450 codeSplittingOptions: {
451 defaultBehavior: [['component'], ['loader']],
452 },
453 routesDirectory: './routes',
454 generatedRouteTree: './routeTree.gen.ts',
455 }),
456 ],
457 server: { middlewareMode: true },
458 appType: 'custom',
459 })
460 const transformed = await server.transformRequest('/routes/page.tsx')
461 // The route module went through the React HMR transforms
462 expect(transformed?.code).toContain('TSRFastRefreshAnchor')
463 await use(await server.ssrLoadModule('/routes/page.tsx'))
464 } finally {
465 await server?.close()
466 await rm(root, { recursive: true, force: true })
467 }
468 }
469β
470 it.each([
471 {
472 name: 'function',
473 declaration: 'export function component() { return null }',
474 options: 'component',
475 exported: { component: ['component'] },
476 },
477 {
478 name: 'overloaded function',
479 declaration:
480 'export function component(): null; export function component() { return null }',
481 options: 'component',
482 exported: { component: ['component'] },
483 },
484 {
485 name: 'function used by two options',
486 declaration: 'export function component() { return null }',
487 options: 'component, errorComponent: component',
488 exported: { component: ['component', 'errorComponent'] },
489 },
490 {
491 name: 'variable',
492 declaration: 'export const component = () => null',
493 options: 'component',
494 exported: { component: ['component'] },
495 },
496 {
497 name: 'class',
498 declaration: `import { Component } from 'react'
499export class component extends Component { render() { return null } }`,
500 options: 'component',
501 exported: { component: ['component'] },
502 },
503 {
504 name: 'variables declared together',
505 declaration:
506 'export const component = () => null, pendingComponent = () => null',
507 options: 'component, pendingComponent',
508 exported: {
509 component: ['component'],
510 pendingComponent: ['pendingComponent'],
511 },
512 },
513 {
514 name: 'aliased',
515 declaration:
516 'function component() { return null }; export { component as View }',
517 options: 'component',
518 exported: { View: ['component'] },
519 },
520 {
521 name: 'default',
522 declaration: 'export default function component() { return null }',
523 options: 'component',
524 exported: { default: ['component'] },
525 },
526 ])(
527 'keep a $name component exported as the route option value',
528 async ({ declaration, options, exported }) => {
529 await withRouteModule(
530 `${head}${declaration}
531export const Route = createFileRoute('/page')({ ${options} })`,
532 (routeModule) => {
533 for (const [name, keys] of Object.entries(exported)) {
534 expect(routeModule).toHaveProperty(name)
535 for (const key of keys) {
536 expect(routeModule[name], `${name} is the ${key} option`).toBe(
537 routeModule.Route.options[key],
538 )
539 }
540 }
541 },
542 )
543 },
544 30_000,
545 )
546β
547 it('keep exported overloads and their aliases that unsplit and split options call', async () => {
548 await withRouteModule(
549 `${head}export function helper(value: string): string
550export function helper(value: number): number
551export function helper(value: string | number) { return value }
552export { helper as helperAlias }
553export const Route = createFileRoute('/page')({
554 component: () => null,
555 beforeLoad: () => helper('before'),
556 loader: () => helper(42),
557})`,
558 async (routeModule) => {
559 expect(routeModule.helperAlias).toBe(routeModule.helper)
560 expect(routeModule.Route.options.beforeLoad()).toBe('before')
561 expect(await routeModule.Route.options.loader()).toBe(42)
562 },
563 )
564 }, 30_000)
565 },
566)