diff --git a/packages/react-start-rsc/tests/rscCssTransform.test.tsx b/packages/react-start-rsc/tests/rscCssTransform.test.tsx index 0e2c2e45cf9..afc4686e948 100644 --- a/packages/react-start-rsc/tests/rscCssTransform.test.tsx +++ b/packages/react-start-rsc/tests/rscCssTransform.test.tsx @@ -161,4 +161,55 @@ describe('RSC CSS compiler transforms', () => { detectKindsInCode(code, 'client', { compilerTransforms }), ).toMatchInlineSnapshot(`Set {}`) }) + + test('rewrites render APIs imported from @tanstack/react-start-rsc', async () => { + const code = await compileWithRscCssTransform({ + code: ` + import { renderServerComponent } from '@tanstack/react-start-rsc' + + export const renderable = renderServerComponent() + `, + }) + + expect(code).toContain( + '__tanstackStartRscCss: import.meta.viteRsc.loadCss()', + ) + }) + + test.each([ + { wrapped: '()', bare: '' }, + { wrapped: ' as any', bare: '' }, + { wrapped: '!', bare: '' }, + { wrapped: '(<>) satisfies unknown', bare: '<>' }, + ])( + 'streams $wrapped like the bare JSX it wraps', + async ({ wrapped, bare }) => { + const compileStream = (element: string) => + compileWithRscCssTransform({ + code: ` + import { renderToReadableStream } from '@tanstack/react-start/rsc' + + export const stream = renderToReadableStream(${element}) + `, + }) + + const bareCode = await compileStream(bare) + expect(bareCode).toContain('import.meta.viteRsc.loadCss()') + expect(await compileStream(wrapped)).toBe(bareCode) + }, + ) + + test('does not stream JSX that is not the whole argument', async () => { + const code = await compileWithRscCssTransform({ + code: ` + import { renderToReadableStream } from '@tanstack/react-start/rsc' + + export const conditional = renderToReadableStream(flag ? : ) + export const spread = renderToReadableStream(...args) + `, + }) + + expect(code).toContain('renderToReadableStream(...args)') + expect(code).not.toContain('loadCss') + }) }) diff --git a/packages/router-generator/tests/transform.test.ts b/packages/router-generator/tests/transform.test.ts index f026ecc30e6..2267599c15e 100644 --- a/packages/router-generator/tests/transform.test.ts +++ b/packages/router-generator/tests/transform.test.ts @@ -13,7 +13,35 @@ function makeNode( } } +function transformToNewRoute(source: string, node = makeNode()) { + return transform({ + source, + ctx: { target: 'react', routeId: '/new', lazy: false }, + node, + }) +} + describe('transform', () => { + it('reads and rewrites the route constructor, id and options through parentheses', () => { + const node = makeNode() + const result = transformToNewRoute( + [ + "import { createLazyFileRoute } from '@tanstack/react-router'", + "export const Route = (createLazyFileRoute)(('/old'))(({ component: Page, server: {} }))", + ].join('\n'), + node, + ) + + expect(result).toEqual({ + result: 'modified', + output: [ + "import { createFileRoute } from '@tanstack/react-router'", + "export const Route = (createFileRoute)(('/new'))(({ component: Page, server: {} }))", + ].join('\n'), + }) + expect(node.createFileRouteProps).toEqual(new Set(['component', 'server'])) + }) + it('updates parenthesized route calls without changing their surrounding source', () => { const result = transform({ source: @@ -535,4 +563,95 @@ describe('transform', () => { ) expect(result.output).not.toContain('createLazyFileRoute') }) + + // The recorded option keys drive prerendering and server-only route pruning. + it('records identifier and string-literal option keys, not computed or spread ones', () => { + const node = makeNode() + const result = transformToNewRoute( + [ + "import { createFileRoute } from '@tanstack/react-router'", + "export const Route = createFileRoute('/new')({ 'component': Page, [key]: load, ...rest, server: {} })", + ].join('\n'), + node, + ) + + expect(result).toEqual({ result: 'not-modified' }) + expect(node.createFileRouteProps).toEqual(new Set(['component', 'server'])) + }) +}) + +// The generator writes its output back over the user's route file, so every +// byte outside the route id and the router import must survive unchanged. +describe('transform preserves the rest of the route file', () => { + it('edits the right spans after a BOM and astral characters', () => { + const result = transformToNewRoute( + [ + '\uFEFF// πŸ˜€', + "import { createLazyFileRoute } from '@tanstack/react-router'", + "import { createFileRoute } from '@tanstack/react-router'", + "export const Route = createFileRoute(/* πŸš€ */ '/old')({})", + ].join('\n'), + ) + + expect(result).toEqual({ + result: 'modified', + output: [ + '\uFEFF// πŸ˜€', + "import { createFileRoute } from '@tanstack/react-router'", + "export const Route = createFileRoute(/* πŸš€ */ '/new')({})", + ].join('\n'), + }) + }) + + it.each([ + { + name: 'a default import', + imports: "import Router from '@tanstack/react-router'", + expected: + "import Router, { createFileRoute } from '@tanstack/react-router'", + }, + { + name: 'an aliased import of the constructor', + imports: + "import { createFileRoute as cfr } from '@tanstack/react-router'", + expected: + "import { createFileRoute as cfr, createFileRoute } from '@tanstack/react-router'", + }, + { + // The constructor goes into the named import, never the namespace one. + name: 'a namespace import', + imports: [ + "import * as Router from '@tanstack/react-router'", + "import { Link } from '@tanstack/react-router'", + ].join('\n'), + expected: [ + "import * as Router from '@tanstack/react-router'", + "import { Link, createFileRoute } from '@tanstack/react-router'", + ].join('\n'), + }, + ])('adds the missing constructor next to $name', ({ imports, expected }) => { + const route = "export const Route = createFileRoute('/old')({})" + + expect(transformToNewRoute(`${imports}\n${route}`)).toEqual({ + result: 'modified', + output: `${expected}\n${route.replace('/old', '/new')}`, + }) + }) + + it('updates only the Route declarator of a multi-declarator export', () => { + const result = transformToNewRoute( + [ + "import { createFileRoute } from '@tanstack/react-router'", + "export const Route = createFileRoute('/old')({}), path = '/old'", + ].join('\n'), + ) + + expect(result).toEqual({ + result: 'modified', + output: [ + "import { createFileRoute } from '@tanstack/react-router'", + "export const Route = createFileRoute('/new')({}), path = '/old'", + ].join('\n'), + }) + }) }) diff --git a/packages/router-plugin/tests/code-splitter-dead-code.test.ts b/packages/router-plugin/tests/code-splitter-dead-code.test.ts new file mode 100644 index 00000000000..038f323caf5 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter-dead-code.test.ts @@ -0,0 +1,462 @@ +import { describe, expect, it } from 'vitest' +import { + compileRouteModules, + declarationOf, + evaluateModule, + expectValidModules, + head, + importSources, + importedNames, + transformWithRouteHmrPlugin, +} from './regression-helpers' + +const sharedModule = 'route.tsx?tsr-shared=1' + +/** Whether a module declares `name` or imports it from the shared module. */ +function binds(module: string, name: string) { + return ( + declarationOf(name).test(module) || + importedNames(module, sharedModule).includes(name) + ) +} + +/** + * The reference module, compiled without and with React HMR: HMR rewrites the + * route options (hoisted components, refresh anchor) before dead code is + * removed, so the removal runs on a different program. + */ +function referenceModules(code: string) { + return { + reference: compileRouteModules(code).modules.reference!, + 'reference with HMR': compileRouteModules(code, { hmr: true }).modules + .reference!, + } +} + +/** + * Renders the split component the way an app loads it: the shared module (if + * any) and the reference module run first, then the component chunk, all + * linked to one instance of the shared module. A top-level statement may then + * reach the component by moving into its chunk or by staying in the + * reference module and writing to a shared binding. + */ +async function renderSplitComponent(modules: Record) { + const stubs: Record> = {} + if (modules.shared) { + stubs[sharedModule] = await evaluateModule(modules.shared) + } + await evaluateModule(modules.reference!, { + ...stubs, + '@tanstack/react-router': { + createFileRoute: () => (options: unknown) => ({ options }), + lazyRouteComponent: () => () => null, + }, + }) + const chunk = await evaluateModule(modules['virtual component']!, stubs) + return chunk.component!() +} + +describe('the reference module only drops code that splitting left unused', () => { + it.each([ + { + name: 'a store subscription that unsubscribes itself', + setup: `import { store } from './store' +const unsubscribe = store.subscribe(() => { + if (store.state.done) unsubscribe() +})`, + declared: ['unsubscribe'], + }, + { + name: 'mutually-referencing declarations', + setup: `import { createPersister } from './persist' +const persister = createPersister({ onRestore: () => restore() }) +function restore() { + persister.restore() +}`, + declared: ['persister', 'restore'], + }, + { + // Source: babel-dead-code-elimination dead-code-elimination.test.ts "only + // eliminates newly unreferenced identifiers", "unexported circular references" + // and "SCC with external caller used -> all preserved" + name: 'unused functions, one calling a helper of the split component', + setup: `function helper() { return 'helper' } +function unused() { return helper() } +function ping(): number { return pong() } +function pong(): number { return ping() }`, + component: '

{helper()}

', + declared: ['helper', 'unused', 'ping', 'pong'], + }, + ])( + 'keeps $name that nothing used before splitting', + async ({ setup, component = '
', declared }) => { + const code = `${head}${setup} +export const Route = createFileRoute('/')({ component: () => ${component} }) +` + const modules = referenceModules(code) + // The validator does not report references to undeclared names. A + // binding the split component reads may come from the shared module. + for (const [module, reference] of Object.entries(modules)) { + for (const name of declared) { + expect(binds(reference, name), `${module} binds ${name}`).toBe(true) + } + } + await expectValidModules(modules) + }, + ) + + // Source: babel-dead-code-elimination dead-code-elimination.test.ts "SCC dead + // code elimination" > "arrow functions in mutual recursion -> removed" + it('moves mutually recursive helpers only the component uses, and their imports, into its chunk', async () => { + const code = `${head}import { dep } from './dep' +const ping = (n: number): number => (n > 0 ? pong(n - 1) : 0) +const pong = function (n: number): number { return n > 0 ? ping(n - 1) : dep } +export const Route = createFileRoute('/')({ + loader: () => 'data', + component: () =>

{ping(3)}

, +}) +` + for (const reference of Object.values(referenceModules(code))) { + expect(reference).not.toMatch(declarationOf('ping')) + expect(reference).not.toMatch(declarationOf('pong')) + expect(importSources(reference)).not.toContain('./dep') + } + const { modules } = compileRouteModules(code) + expect(modules['virtual component']).toMatch(declarationOf('ping')) + expect(modules['virtual component']).toMatch(declarationOf('pong')) + await expectValidModules(modules) + }) + + // Source: Next.js ssg/getStaticProps/should-remove-re-exported-function-declarations-dependents-variables-functions-imports + it('keeps the import specifiers nothing used before splitting', async () => { + const { modules } = + compileRouteModules(`${head}import { used, preUnused } from 'bar' +const b = function apples() { return used } +export const Route = createFileRoute('/')({ + loader: () => 'data', + component: () =>

{b()}

, +}) +`) + expect(importedNames(modules.reference!, 'bar')).toEqual(['preUnused']) + expect(modules.reference).not.toContain('apples') + expect(modules['virtual component']).toMatch(declarationOf('b')) + expect(importedNames(modules['virtual component']!, 'bar')).toContain( + 'used', + ) + await expectValidModules(modules) + }) + + // Source: React Router route-chunks-test.ts "shared imports across chunks but + // not main chunk with shared side effect usage" + it('runs a top-level call only in the reference module, even when the chunks import its callee', async () => { + const { modules } = + compileRouteModules(`${head}import { shared } from './shared' +shared('side-effect-marker') +export const Route = createFileRoute('/')({ + component: () =>
{shared('component')}
, + errorComponent: () =>
{shared('error')}
, +}) +`) + expect(modules.reference).toContain('side-effect-marker') + expect(modules['virtual component']).not.toContain('side-effect-marker') + expect(modules['virtual errorComponent']).not.toContain( + 'side-effect-marker', + ) + await expectValidModules(modules) + }) + + // TypeScript erases type positions, so a declaration whose binding only + // appears in a type is still live code that runs when the route loads. + it.each([ + { + name: 'the reference module', + compile: (code: string) => compileRouteModules(code).modules.reference!, + }, + { + name: 'a route module compiled for HMR', + compile: (code: string) => transformWithRouteHmrPlugin(code), + }, + ])( + 'keeps a declaration only referenced from types in $name', + async ({ compile }) => { + const output = + compile(`${head}import { registerAnalytics } from './analytics' +const analytics = registerAnalytics('/posts') +declare module './analytics' { + interface Registry { + posts: typeof analytics + } +} +export const Route = createFileRoute('/posts')({ + component: () =>

posts

, +}) +`) + expect(output).toMatch(declarationOf('analytics')) + expect(output).toContain('registerAnalytics(') + await expectValidModules({ output }) + }, + ) +}) + +describe('code a split option needs moves with it', () => { + // Source: Qwik optimizer test.rs should_not_move_over_side_effects, + // example_drop_side_effects; Turbopack tree-shaker analyzer/route-kind + it.each([ + { + name: 'a compound component member assignment', + setup: `function Card({ children }) { return
{children}
} +Card.Title = function Title() { return

t

}`, + render: '', + rendered: '

t

', + }, + { + name: 'a registry filled by a top-level call', + setup: `const registry = new Map() +registry.set('a', 'A')`, + render: `

{registry.get('a')}

`, + rendered: '

A

', + }, + { + name: 'a compiled enum initializing a var', + setup: `var Kind: any +;(function (Kind: any) { + Kind['A'] = 'a' +})(Kind || (Kind = {}))`, + render: '

{Kind.A}

', + rendered: '

a

', + }, + ])( + 'renders a split component that relies on $name', + async ({ setup, render, rendered }) => { + const { modules } = compileRouteModules(`${head}${setup} +export const Route = createFileRoute('/')({ + component: () => ${render}, +}) +`) + await expectValidModules(modules) + expect(await renderSplitComponent(modules)).toBe(rendered) + }, + ) + + // Source: React Compiler hook-ref-callback.js and + // dont-memoize-primitive-function-call-non-escaping.js: a function shared by + // the loader and the split component declares a local it never reads. + it.each([ + { name: 'a call', initializer: 'track(id)' }, + { name: 'an optional call', initializer: 'track?.(id)' }, + ])( + 'keeps an unused local initialized by $name in a shared function', + async ({ initializer }) => { + const { modules } = + compileRouteModules(`${head}import { track } from './track' +function useShared(id) { + const unused = ${initializer} + return id +} +export const Route = createFileRoute('/')({ + loader: () => useShared('loader'), + component: () =>

{useShared('component')}

, +}) +`) + const calls: Array = [] + const shared = await evaluateModule(modules.shared!, { + './track': { track: (label: string) => calls.push(label) }, + }) + expect(shared.useShared!('render')).toBe('render') + expect(calls).toEqual(['render']) + }, + ) + + // Source: babel-dead-code-elimination dead-code-elimination.test.ts "object + // pattern" > "within function param" + it('keeps empty destructuring parameters of helpers moved into the chunk', async () => { + const { modules } = + compileRouteModules(`${head}function f(a: any, {}: any) { return a } +const g = (a: any, []: any) => a +export const Route = createFileRoute('/')({ + loader: () => 'data', + component: () =>

{f.length}{g.length}

, +}) +`) + const chunk = await evaluateModule(modules['virtual component']!) + expect(chunk.component!()).toBe('

22

') + }) + + // Source: React Router remove-exports-test.ts "iife with dependencies" + it('moves a component created by an IIFE with its dependencies and shares the helper the loader uses too', async () => { + const { modules, sharedBindings } = + compileRouteModules(`${head}import { removedLib } from 'removed-lib' +import { keptLib } from 'kept-lib' +import { sharedLib } from 'shared-lib' +const sharedUtil = (value?: unknown) => sharedLib(value) +const removedUtil = () => sharedUtil(removedLib()) +const keptUtil = () => sharedUtil(keptLib()) +const Page = (() => { + const message = removedUtil() + return () =>
{String(message)}
+})() +export const Route = createFileRoute('/')({ + loader: () => keptUtil(), + component: Page, +}) +`) + expect(sharedBindings).toEqual(['sharedUtil']) + expect(importSources(modules.reference!)).toEqual([ + '@tanstack/react-router', + 'kept-lib', + 'route.tsx?tsr-shared=1', + ]) + expect(modules.reference).not.toContain('removedUtil') + expect(importSources(modules['virtual component']!)).toEqual([ + 'removed-lib', + 'route.tsx?tsr-shared=1', + ]) + expect(modules['virtual component']).toMatch(declarationOf('Page')) + expect(importSources(modules.shared!)).toEqual(['shared-lib']) + await expectValidModules(modules) + }) + + // Source: React Router route-chunks-test.ts "isolated exported variable + // declarations sharing an export statement"; Next.js + // ssg/getStaticProps/should-remove-re-exported-variable-declarations-safe + it.each([ + { + name: 'plain declarators', + declarations: `const Page = () =>
{chunkMessage}
, + main = mainMessage`, + }, + { + name: 'destructured declarators', + declarations: `const { Page } = { Page: () =>
{chunkMessage}
}, + { main } = { main: mainMessage }`, + }, + ])( + 'gives each of the $name of one statement to the module that reads it', + async ({ declarations }) => { + const { modules, sharedBindings } = + compileRouteModules(`${head}import { chunkMessage, mainMessage } from './messages' +${declarations} +export const Route = createFileRoute('/')({ + loader: () => main, + component: Page, +}) +`) + expect(sharedBindings).toEqual([]) + expect(importedNames(modules.reference!, './messages')).toEqual([ + 'mainMessage', + ]) + expect(modules.reference).not.toMatch(/\bPage\b/) + expect( + importedNames(modules['virtual component']!, './messages'), + ).toEqual(['chunkMessage']) + expect(modules['virtual component']).not.toMatch(/\bmain\b/) + await expectValidModules(modules) + }, + ) + + // Source: React Router route-chunks-test.ts "exported variable declarations + // sharing an export statement" + it('shares a declarator that a sibling declarator reads', async () => { + const { modules, sharedBindings } = + compileRouteModules(`${head}import { sharedMessage } from './messages' +const Page = () =>
{sharedMessage}
, + Preview = Page +export const Route = createFileRoute('/')({ + loader: () => Preview.name, + component: Page, +}) +`) + expect(sharedBindings).toEqual(['Page']) + expect(modules.shared).toMatch(declarationOf('Page')) + expect(modules.reference).toMatch(declarationOf('Preview')) + expect(importedNames(modules.reference!, sharedModule)).toEqual(['Page']) + expect(modules.reference).not.toMatch(declarationOf('Page')) + expect(modules['virtual component']).not.toMatch(declarationOf('Page')) + await expectValidModules(modules) + }) +}) + +describe('var declarations nested in top-level statements', () => { + it.each([ + { + name: 'a for loop head', + setup: 'for (var value = 0; value < 3; value++) {}', + }, + { name: 'a for-of head', setup: "for (var value of ['a']) {}" }, + { + name: 'an if block', + setup: "if (typeof window === 'undefined') { var value = 'server' }", + }, + ])( + 'stay bound in every module when $name declares a binding the loader and the component read', + async ({ setup }) => { + const { modules } = compileRouteModules(`${head}${setup} +export const Route = createFileRoute('/')({ + loader: () => value, + component: () =>
{value}
, +}) +`) + // Known limitation on main: the statement runs in both modules instead + // of once in the shared module; only check that each module binds `value`. + for (const name of ['reference', 'virtual component']) { + expect(binds(modules[name]!, 'value'), `${name} binds value`).toBe(true) + } + await expectValidModules(modules) + }, + ) + + it('stay bound in the reference module when exported and read by the component', async () => { + const { modules } = + compileRouteModules(`${head}if (typeof window === 'undefined') { var flag = 'server' } +export { flag } +export const Route = createFileRoute('/')({ + component: () =>
{flag}
, +}) +`) + expect(binds(modules.reference!, 'flag')).toBe(true) + await expectValidModules(modules) + }) + + // Source: babel-dead-code-elimination dead-code-elimination.test.ts "variable" + // (var bindings declared inside nested statements) + it('follow the only option that reads them', async () => { + const { modules } = + compileRouteModules(`${head}import { compute, connect } from './lib' +if (typeof window !== 'undefined') { + var flag = compute() +} +for (var index = 0; index < 3; index++) {} +{ + var block = connect() +} +export const Route = createFileRoute('/')({ + loader: () => block, + component: () =>

{String(flag)}{index}

, +}) +`) + expect(modules.reference).not.toContain('compute()') + expect(modules.reference).toMatch(declarationOf('block')) + const chunk = modules['virtual component']! + expect(chunk).toMatch(declarationOf('flag')) + expect(chunk).toMatch(declarationOf('index')) + expect(chunk).not.toContain('connect()') + await expectValidModules(modules) + }) +}) + +describe('robustness', () => { + it('compiles a route with a long method chain', async () => { + // Builder APIs (schemas, query builders) produce deep left-nested calls + const chain = Array.from({ length: 200 }, (_, i) => `.add(${i})`).join('') + const { modules } = + compileRouteModules(`${head}import { builder } from './builder' +const schema = builder()${chain} +export const Route = createFileRoute('/')({ + loader: () => schema, + component: () =>
{String(schema)}
, +}) +`) + expect(modules.shared).toContain('.add(199)') + await expectValidModules(modules) + }) +}) diff --git a/packages/router-plugin/tests/code-splitter-imports-exports.test.ts b/packages/router-plugin/tests/code-splitter-imports-exports.test.ts new file mode 100644 index 00000000000..b679782bdc8 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter-imports-exports.test.ts @@ -0,0 +1,330 @@ +import { transformWithOxc } from 'vite' +import { describe, expect, it } from 'vitest' +import { + compileRouteModules, + componentChunk, + declarationOf, + evaluateModule, + expectValidModules, + exportedNames, + head, + importSources, + importedNames, + transformWithRouteHmrPlugin, +} from './regression-helpers' + +describe('each module imports only the specifiers it reads', () => { + // Source: React Router route-chunks-test.ts "functions referencing their own + // identifiers"; babel-dead-code-elimination dead-code-elimination.test.ts + // "import" > "mixed default and named" and "namespace" + it('splits default, named and namespace specifiers between the modules', async () => { + const { modules, sharedBindings } = + compileRouteModules(`${head}import defaultMessage, { targetMessage, otherMessage } from './messages' +import * as messages from './messages' +import other, * as ns from './other' +const getDefault = () => defaultMessage +const getTarget = () => targetMessage +const getOther = () => otherMessage +function getNamespaced() { + return messages.namespaced +} +export const Route = createFileRoute('/')({ + loader: () => [getOther(), other], + component: () =>
{getDefault()}{ns.x}
, + errorComponent: () =>
{getNamespaced()}
, + notFoundComponent: () =>
{getTarget()}
, +}) +`) + expect(sharedBindings).toEqual([]) + const imports = (module: string, source: string) => + importedNames(modules[module]!, source) + expect(imports('reference', './messages')).toEqual(['otherMessage']) + expect(imports('reference', './other')).toEqual(['default']) + expect(imports('virtual component', './messages')).toEqual(['default']) + expect(imports('virtual component', './other')).toEqual(['*']) + expect(imports('virtual errorComponent', './messages')).toEqual(['*']) + expect(imports('virtual notFoundComponent', './messages')).toEqual([ + 'targetMessage', + ]) + await expectValidModules(modules) + }) + + it('moves a specifier with a string name into the chunk', async () => { + const { modules } = + compileRouteModules(`${head}import { "kebab-name" as Kebab } from './icons' +export const Route = createFileRoute('/')({ + loader: () => 'data', + component: () => , +}) +`) + expect(importedNames(modules['virtual component']!, './icons')).toEqual([ + 'kebab-name', + ]) + expect(importSources(modules.reference!)).not.toContain('./icons') + await expectValidModules(modules) + }) + + // Source: babel-dead-code-elimination dead-code-elimination.test.ts "import" > + // "mixed default and named: none used" and "side-effect" + it('removes an import whose specifiers all moved instead of leaving a side-effect import', async () => { + const code = `${head}import a, { b } from 'pkg' +import './styles.css' +export const Route = createFileRoute('/')({ + loader: () => 'data', + component: () =>

{a}{b}

, +}) +` + const { modules } = compileRouteModules(code) + // React HMR rewrites the reference module before unused code is removed. + const hmrReference = compileRouteModules(code, { hmr: true }).modules + .reference! + for (const reference of [modules.reference!, hmrReference]) { + expect(importSources(reference)).toContain('./styles.css') + expect(importSources(reference)).not.toContain('pkg') + } + expect(importedNames(modules['virtual component']!, 'pkg')).toEqual([ + 'b', + 'default', + ]) + await expectValidModules(modules) + }) + + // With React's classic JSX runtime (`jsx: "react"` in tsconfig), JSX + // compiles to `React.createElement`, so a React import that the TypeScript + // code only uses in types must stay. + it.each([ + { name: 'split chunk', compile: componentChunk }, + { + name: 'route module compiled for HMR', + compile: (code: string) => transformWithRouteHmrPlugin(code), + }, + ])( + 'keeps the React import of the $name for classic JSX', + async ({ compile }) => { + const output = compile(`import * as React from 'react' +${head}function Page({ title = 'classic' }: { title?: React.ReactNode }) { + return

{title}

+} +export const Route = createFileRoute('/')({ component: Page }) +`) + const { code } = await transformWithOxc(output, 'module.tsx', { + jsx: { runtime: 'classic' }, + }) + expect(importedNames(code, 'react')).toEqual(['*']) + }, + ) +}) + +describe('exports of the route file', () => { + it.each([ + { name: 'as-is', exports: 'export { Foo }' }, + { name: 'renamed', exports: 'export { Foo as Bar }' }, + ])( + 'are not redeclared when they re-export an import $name', + async ({ exports }) => { + const { modules } = + compileRouteModules(`${head}import { Foo } from './foo' +${exports} +export const Route = createFileRoute('/')({ component: Page }) +function Page() { + return +} +`) + await expectValidModules(modules) + }, + ) + + it('are not redeclared when destructured next to a non-exported binding', async () => { + const { modules } = compileRouteModules(`${head}const { a, b } = getStuff() +export { a } +export const Route = createFileRoute('/')({ + component: () =>
{a}{b}
, +}) +`) + await expectValidModules(modules) + }) + + it.each([ + { name: 'function', declaration: 'function () {\n return null\n}' }, + { name: 'class', declaration: 'class {\n x = 1\n}' }, + ])( + 'keep an anonymous default-exported $name valid in every module', + async ({ declaration }) => { + const { modules } = compileRouteModules(`${head}const cache = new Map() +function Page() { + return
{cache.size}
+} +export const Route = createFileRoute('/')({ + loader: () => cache.get('x'), + component: Page, +}) +export default ${declaration} +`) + expect(Object.keys(modules)).toContain('shared') + await expectValidModules(modules) + }, + ) + + // Source: Next.js ssg/getStaticProps/issue-31855 and multi-declarator-export + it('are imported by the chunk when declared in one statement', async () => { + const { modules } = compileRouteModules(`${head}export const a = 1, + b = 2 +export const Route = createFileRoute('/')({ + component: () =>
{a + b}
, +}) +`) + expect(exportedNames(modules.reference!)).toEqual(['Route', 'a', 'b']) + const chunk = modules['virtual component']! + // From the route module, or from the shared module the route module + // re-exports them from. + expect( + [ + ...importedNames(chunk, 'route.tsx'), + ...importedNames(chunk, 'route.tsx?tsr-shared=1'), + ].sort(), + ).toEqual(['a', 'b']) + expect(chunk).not.toMatch(declarationOf('a')) + expect(chunk).not.toMatch(declarationOf('b')) + await expectValidModules(modules) + }) + + it('keep module-level re-exports in the reference module', async () => { + const { modules } = compileRouteModules(`${head}export * from './lib' +export * as lib from './lib' +export {} +const cache = new Map() +export const Route = createFileRoute('/')({ + loader: () => cache.size, + component: () =>
{cache.size}
, +}) +`) + expect(modules.reference).toMatch(/export \* from ['"]\.\/lib['"]/) + expect(modules.reference).toMatch(/export \* as lib from ['"]\.\/lib['"]/) + await expectValidModules(modules) + }) +}) + +describe('TypeScript-only syntax', () => { + it('erases type-only imports and exports from the split modules', async () => { + const { modules } = + compileRouteModules(`${head}import type { User } from './types' +import { type Settings, defaults } from './settings' +export type * from './types' +export type { User } +const current: User | Settings = defaults +export const Route = createFileRoute('/')({ + loader: () => current, + component: () =>
{String(current)}
, +}) +`) + expect(importedNames(modules['virtual component']!, './types')).toEqual([]) + expect(importedNames(modules.shared!, './types')).toEqual([]) + expect(importedNames(modules.shared!, './settings')).toEqual(['defaults']) + await expectValidModules(modules) + }) + + // Ambient declarations (`declare ...`) have no runtime binding: the + // environment provides the value (a