Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 compileRouteModules,
4 declarationOf,
5 evaluateModule,
6 expectValidModules,
7 head,
8 importSources,
9 importedNames,
10 transformWithRouteHmrPlugin,
11} from './regression-helpers'
12β
13const sharedModule = 'route.tsx?tsr-shared=1'
14β
15/** Whether a module declares `name` or imports it from the shared module. */
16function binds(module: string, name: string) {
17 return (
18 declarationOf(name).test(module) ||
19 importedNames(module, sharedModule).includes(name)
20 )
21}
22β
23/**
24 * The reference module, compiled without and with React HMR: HMR rewrites the
25 * route options (hoisted components, refresh anchor) before dead code is
26 * removed, so the removal runs on a different program.
27 */
28function referenceModules(code: string) {
29 return {
30 reference: compileRouteModules(code).modules.reference!,
31 'reference with HMR': compileRouteModules(code, { hmr: true }).modules
32 .reference!,
33 }
34}
35β
36/**
37 * Renders the split component the way an app loads it: the shared module (if
38 * any) and the reference module run first, then the component chunk, all
39 * linked to one instance of the shared module. A top-level statement may then
40 * reach the component by moving into its chunk or by staying in the
41 * reference module and writing to a shared binding.
42 */
43async function renderSplitComponent(modules: Record<string, string>) {
44 const stubs: Record<string, Record<string, unknown>> = {}
45 if (modules.shared) {
46 stubs[sharedModule] = await evaluateModule(modules.shared)
47 }
48 await evaluateModule(modules.reference!, {
49 ...stubs,
50 '@tanstack/react-router': {
51 createFileRoute: () => (options: unknown) => ({ options }),
52 lazyRouteComponent: () => () => null,
53 },
54 })
55 const chunk = await evaluateModule(modules['virtual component']!, stubs)
56 return chunk.component!()
57}
58β
59describe('the reference module only drops code that splitting left unused', () => {
60 it.each([
61 {
62 name: 'a store subscription that unsubscribes itself',
63 setup: `import { store } from './store'
64const unsubscribe = store.subscribe(() => {
65 if (store.state.done) unsubscribe()
66})`,
67 declared: ['unsubscribe'],
68 },
69 {
70 name: 'mutually-referencing declarations',
71 setup: `import { createPersister } from './persist'
72const persister = createPersister({ onRestore: () => restore() })
73function restore() {
74 persister.restore()
75}`,
76 declared: ['persister', 'restore'],
77 },
78 {
79 // Source: babel-dead-code-elimination dead-code-elimination.test.ts "only
80 // eliminates newly unreferenced identifiers", "unexported circular references"
81 // and "SCC with external caller used -> all preserved"
82 name: 'unused functions, one calling a helper of the split component',
83 setup: `function helper() { return 'helper' }
84function unused() { return helper() }
85function ping(): number { return pong() }
86function pong(): number { return ping() }`,
87 component: '<p>{helper()}</p>',
88 declared: ['helper', 'unused', 'ping', 'pong'],
89 },
90 ])(
91 'keeps $name that nothing used before splitting',
92 async ({ setup, component = '<div />', declared }) => {
93 const code = `${head}${setup}
94export const Route = createFileRoute('/')({ component: () => ${component} })
95`
96 const modules = referenceModules(code)
97 // The validator does not report references to undeclared names. A
98 // binding the split component reads may come from the shared module.
99 for (const [module, reference] of Object.entries(modules)) {
100 for (const name of declared) {
101 expect(binds(reference, name), `${module} binds ${name}`).toBe(true)
102 }
103 }
104 await expectValidModules(modules)
105 },
106 )
107β
108 // Source: babel-dead-code-elimination dead-code-elimination.test.ts "SCC dead
109 // code elimination" > "arrow functions in mutual recursion -> removed"
110 it('moves mutually recursive helpers only the component uses, and their imports, into its chunk', async () => {
111 const code = `${head}import { dep } from './dep'
112const ping = (n: number): number => (n > 0 ? pong(n - 1) : 0)
113const pong = function (n: number): number { return n > 0 ? ping(n - 1) : dep }
114export const Route = createFileRoute('/')({
115 loader: () => 'data',
116 component: () => <p>{ping(3)}</p>,
117})
118`
119 for (const reference of Object.values(referenceModules(code))) {
120 expect(reference).not.toMatch(declarationOf('ping'))
121 expect(reference).not.toMatch(declarationOf('pong'))
122 expect(importSources(reference)).not.toContain('./dep')
123 }
124 const { modules } = compileRouteModules(code)
125 expect(modules['virtual component']).toMatch(declarationOf('ping'))
126 expect(modules['virtual component']).toMatch(declarationOf('pong'))
127 await expectValidModules(modules)
128 })
129β
130 // Source: Next.js ssg/getStaticProps/should-remove-re-exported-function-declarations-dependents-variables-functions-imports
131 it('keeps the import specifiers nothing used before splitting', async () => {
132 const { modules } =
133 compileRouteModules(`${head}import { used, preUnused } from 'bar'
134const b = function apples() { return used }
135export const Route = createFileRoute('/')({
136 loader: () => 'data',
137 component: () => <p>{b()}</p>,
138})
139`)
140 expect(importedNames(modules.reference!, 'bar')).toEqual(['preUnused'])
141 expect(modules.reference).not.toContain('apples')
142 expect(modules['virtual component']).toMatch(declarationOf('b'))
143 expect(importedNames(modules['virtual component']!, 'bar')).toContain(
144 'used',
145 )
146 await expectValidModules(modules)
147 })
148β
149 // Source: React Router route-chunks-test.ts "shared imports across chunks but
150 // not main chunk with shared side effect usage"
151 it('runs a top-level call only in the reference module, even when the chunks import its callee', async () => {
152 const { modules } =
153 compileRouteModules(`${head}import { shared } from './shared'
154shared('side-effect-marker')
155export const Route = createFileRoute('/')({
156 component: () => <div>{shared('component')}</div>,
157 errorComponent: () => <div>{shared('error')}</div>,
158})
159`)
160 expect(modules.reference).toContain('side-effect-marker')
161 expect(modules['virtual component']).not.toContain('side-effect-marker')
162 expect(modules['virtual errorComponent']).not.toContain(
163 'side-effect-marker',
164 )
165 await expectValidModules(modules)
166 })
167β
168 // TypeScript erases type positions, so a declaration whose binding only
169 // appears in a type is still live code that runs when the route loads.
170 it.each([
171 {
172 name: 'the reference module',
173 compile: (code: string) => compileRouteModules(code).modules.reference!,
174 },
175 {
176 name: 'a route module compiled for HMR',
177 compile: (code: string) => transformWithRouteHmrPlugin(code),
178 },
179 ])(
180 'keeps a declaration only referenced from types in $name',
181 async ({ compile }) => {
182 const output =
183 compile(`${head}import { registerAnalytics } from './analytics'
184const analytics = registerAnalytics('/posts')
185declare module './analytics' {
186 interface Registry {
187 posts: typeof analytics
188 }
189}
190export const Route = createFileRoute('/posts')({
191 component: () => <p>posts</p>,
192})
193`)
194 expect(output).toMatch(declarationOf('analytics'))
195 expect(output).toContain('registerAnalytics(')
196 await expectValidModules({ output })
197 },
198 )
199})
200β
201describe('code a split option needs moves with it', () => {
202 // Source: Qwik optimizer test.rs should_not_move_over_side_effects,
203 // example_drop_side_effects; Turbopack tree-shaker analyzer/route-kind
204 it.each([
205 {
206 name: 'a compound component member assignment',
207 setup: `function Card({ children }) { return <div>{children}</div> }
208Card.Title = function Title() { return <h1>t</h1> }`,
209 render: '<Card><Card.Title /></Card>',
210 rendered: '<div><h1>t</h1></div>',
211 },
212 {
213 name: 'a registry filled by a top-level call',
214 setup: `const registry = new Map()
215registry.set('a', 'A')`,
216 render: `<p>{registry.get('a')}</p>`,
217 rendered: '<p>A</p>',
218 },
219 {
220 name: 'a compiled enum initializing a var',
221 setup: `var Kind: any
222;(function (Kind: any) {
223 Kind['A'] = 'a'
224})(Kind || (Kind = {}))`,
225 render: '<p>{Kind.A}</p>',
226 rendered: '<p>a</p>',
227 },
228 ])(
229 'renders a split component that relies on $name',
230 async ({ setup, render, rendered }) => {
231 const { modules } = compileRouteModules(`${head}${setup}
232export const Route = createFileRoute('/')({
233 component: () => ${render},
234})
235`)
236 await expectValidModules(modules)
237 expect(await renderSplitComponent(modules)).toBe(rendered)
238 },
239 )
240β
241 // Source: React Compiler hook-ref-callback.js and
242 // dont-memoize-primitive-function-call-non-escaping.js: a function shared by
243 // the loader and the split component declares a local it never reads.
244 it.each([
245 { name: 'a call', initializer: 'track(id)' },
246 { name: 'an optional call', initializer: 'track?.(id)' },
247 ])(
248 'keeps an unused local initialized by $name in a shared function',
249 async ({ initializer }) => {
250 const { modules } =
251 compileRouteModules(`${head}import { track } from './track'
252function useShared(id) {
253 const unused = ${initializer}
254 return id
255}
256export const Route = createFileRoute('/')({
257 loader: () => useShared('loader'),
258 component: () => <p>{useShared('component')}</p>,
259})
260`)
261 const calls: Array<string> = []
262 const shared = await evaluateModule(modules.shared!, {
263 './track': { track: (label: string) => calls.push(label) },
264 })
265 expect(shared.useShared!('render')).toBe('render')
266 expect(calls).toEqual(['render'])
267 },
268 )
269β
270 // Source: babel-dead-code-elimination dead-code-elimination.test.ts "object
271 // pattern" > "within function param"
272 it('keeps empty destructuring parameters of helpers moved into the chunk', async () => {
273 const { modules } =
274 compileRouteModules(`${head}function f(a: any, {}: any) { return a }
275const g = (a: any, []: any) => a
276export const Route = createFileRoute('/')({
277 loader: () => 'data',
278 component: () => <p>{f.length}{g.length}</p>,
279})
280`)
281 const chunk = await evaluateModule(modules['virtual component']!)
282 expect(chunk.component!()).toBe('<p>22</p>')
283 })
284β
285 // Source: React Router remove-exports-test.ts "iife with dependencies"
286 it('moves a component created by an IIFE with its dependencies and shares the helper the loader uses too', async () => {
287 const { modules, sharedBindings } =
288 compileRouteModules(`${head}import { removedLib } from 'removed-lib'
289import { keptLib } from 'kept-lib'
290import { sharedLib } from 'shared-lib'
291const sharedUtil = (value?: unknown) => sharedLib(value)
292const removedUtil = () => sharedUtil(removedLib())
293const keptUtil = () => sharedUtil(keptLib())
294const Page = (() => {
295 const message = removedUtil()
296 return () => <div>{String(message)}</div>
297})()
298export const Route = createFileRoute('/')({
299 loader: () => keptUtil(),
300 component: Page,
301})
302`)
303 expect(sharedBindings).toEqual(['sharedUtil'])
304 expect(importSources(modules.reference!)).toEqual([
305 '@tanstack/react-router',
306 'kept-lib',
307 'route.tsx?tsr-shared=1',
308 ])
309 expect(modules.reference).not.toContain('removedUtil')
310 expect(importSources(modules['virtual component']!)).toEqual([
311 'removed-lib',
312 'route.tsx?tsr-shared=1',
313 ])
314 expect(modules['virtual component']).toMatch(declarationOf('Page'))
315 expect(importSources(modules.shared!)).toEqual(['shared-lib'])
316 await expectValidModules(modules)
317 })
318β
319 // Source: React Router route-chunks-test.ts "isolated exported variable
320 // declarations sharing an export statement"; Next.js
321 // ssg/getStaticProps/should-remove-re-exported-variable-declarations-safe
322 it.each([
323 {
324 name: 'plain declarators',
325 declarations: `const Page = () => <div>{chunkMessage}</div>,
326 main = mainMessage`,
327 },
328 {
329 name: 'destructured declarators',
330 declarations: `const { Page } = { Page: () => <div>{chunkMessage}</div> },
331 { main } = { main: mainMessage }`,
332 },
333 ])(
334 'gives each of the $name of one statement to the module that reads it',
335 async ({ declarations }) => {
336 const { modules, sharedBindings } =
337 compileRouteModules(`${head}import { chunkMessage, mainMessage } from './messages'
338${declarations}
339export const Route = createFileRoute('/')({
340 loader: () => main,
341 component: Page,
342})
343`)
344 expect(sharedBindings).toEqual([])
345 expect(importedNames(modules.reference!, './messages')).toEqual([
346 'mainMessage',
347 ])
348 expect(modules.reference).not.toMatch(/\bPage\b/)
349 expect(
350 importedNames(modules['virtual component']!, './messages'),
351 ).toEqual(['chunkMessage'])
352 expect(modules['virtual component']).not.toMatch(/\bmain\b/)
353 await expectValidModules(modules)
354 },
355 )
356β
357 // Source: React Router route-chunks-test.ts "exported variable declarations
358 // sharing an export statement"
359 it('shares a declarator that a sibling declarator reads', async () => {
360 const { modules, sharedBindings } =
361 compileRouteModules(`${head}import { sharedMessage } from './messages'
362const Page = () => <div>{sharedMessage}</div>,
363 Preview = Page
364export const Route = createFileRoute('/')({
365 loader: () => Preview.name,
366 component: Page,
367})
368`)
369 expect(sharedBindings).toEqual(['Page'])
370 expect(modules.shared).toMatch(declarationOf('Page'))
371 expect(modules.reference).toMatch(declarationOf('Preview'))
372 expect(importedNames(modules.reference!, sharedModule)).toEqual(['Page'])
373 expect(modules.reference).not.toMatch(declarationOf('Page'))
374 expect(modules['virtual component']).not.toMatch(declarationOf('Page'))
375 await expectValidModules(modules)
376 })
377})
378β
379describe('var declarations nested in top-level statements', () => {
380 it.each([
381 {
382 name: 'a for loop head',
383 setup: 'for (var value = 0; value < 3; value++) {}',
384 },
385 { name: 'a for-of head', setup: "for (var value of ['a']) {}" },
386 {
387 name: 'an if block',
388 setup: "if (typeof window === 'undefined') { var value = 'server' }",
389 },
390 ])(
391 'stay bound in every module when $name declares a binding the loader and the component read',
392 async ({ setup }) => {
393 const { modules } = compileRouteModules(`${head}${setup}
394export const Route = createFileRoute('/')({
395 loader: () => value,
396 component: () => <div>{value}</div>,
397})
398`)
399 // Known limitation on main: the statement runs in both modules instead
400 // of once in the shared module; only check that each module binds `value`.
401 for (const name of ['reference', 'virtual component']) {
402 expect(binds(modules[name]!, 'value'), `${name} binds value`).toBe(true)
403 }
404 await expectValidModules(modules)
405 },
406 )
407β
408 it('stay bound in the reference module when exported and read by the component', async () => {
409 const { modules } =
410 compileRouteModules(`${head}if (typeof window === 'undefined') { var flag = 'server' }
411export { flag }
412export const Route = createFileRoute('/')({
413 component: () => <div>{flag}</div>,
414})
415`)
416 expect(binds(modules.reference!, 'flag')).toBe(true)
417 await expectValidModules(modules)
418 })
419β
420 // Source: babel-dead-code-elimination dead-code-elimination.test.ts "variable"
421 // (var bindings declared inside nested statements)
422 it('follow the only option that reads them', async () => {
423 const { modules } =
424 compileRouteModules(`${head}import { compute, connect } from './lib'
425if (typeof window !== 'undefined') {
426 var flag = compute()
427}
428for (var index = 0; index < 3; index++) {}
429{
430 var block = connect()
431}
432export const Route = createFileRoute('/')({
433 loader: () => block,
434 component: () => <p>{String(flag)}{index}</p>,
435})
436`)
437 expect(modules.reference).not.toContain('compute()')
438 expect(modules.reference).toMatch(declarationOf('block'))
439 const chunk = modules['virtual component']!
440 expect(chunk).toMatch(declarationOf('flag'))
441 expect(chunk).toMatch(declarationOf('index'))
442 expect(chunk).not.toContain('connect()')
443 await expectValidModules(modules)
444 })
445})
446β
447describe('robustness', () => {
448 it('compiles a route with a long method chain', async () => {
449 // Builder APIs (schemas, query builders) produce deep left-nested calls
450 const chain = Array.from({ length: 200 }, (_, i) => `.add(${i})`).join('')
451 const { modules } =
452 compileRouteModules(`${head}import { builder } from './builder'
453const schema = builder()${chain}
454export const Route = createFileRoute('/')({
455 loader: () => schema,
456 component: () => <div>{String(schema)}</div>,
457})
458`)
459 expect(modules.shared).toContain('.add(199)')
460 await expectValidModules(modules)
461 })
462})