Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

code-splitter-dead-code.test.ts

544 lines19.2 KB

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 )
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 }
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!()
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} })
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})
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 }
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 // Inputs adapted from babel-dead-code-elimination dead-code-elimination.test.ts
201 // "object pattern" and "array pattern" > "unzips if all variables are
202 // unused", which removes the whole declaration: an empty pattern declares
203 // nothing, so splitting never left it unused and its initializer still runs.
204 it('keeps the initializers of empty destructuring patterns', async () => {
205 const { modules } =
206 compileRouteModules(`${head}import { init, other } from './init'
207const {} = init()
208const [] = other()
209const { a: {} } = init()
210export const Route = createFileRoute('/')({
211 loader: () => 'data',
212 component: () => <p>component</p>,
213})
214`)
215 expect(modules.reference!.match(/\binit\(\)/g)).toHaveLength(2)
216 expect(modules.reference).toContain('other()')
217 expect(importSources(modules['virtual component']!)).not.toContain('./init')
218 await expectValidModules(modules)
219 })
220})
221​
222describe('code a split option needs moves with it', () => {
223 // Inputs adapted from babel-dead-code-elimination dead-code-elimination.test.ts
224 // "function" > "declaration" and "variable" > "identifier"
225 it.each([
226 {
227 name: 'an overloaded function',
228 declarations: `function load(id: string): string
229function load(id: number): string
230function load(id: any) { return lib.x(id) }`,
231 render: '{load(1)}',
232 },
233 {
234 name: 'a redeclared var',
235 declarations: `var load = lib.a()
236var load = lib.b()`,
237 render: '{load}',
238 },
239 ])(
240 'moves $name only the split component uses, and its import, into its chunk',
241 async ({ declarations, render }) => {
242 const { modules } =
243 compileRouteModules(`${head}import { lib } from './lib'
244${declarations}
245export const Route = createFileRoute('/')({
246 loader: () => 'data',
247 component: () => <p>${render}</p>,
248})
249`)
250 expect(importSources(modules.reference!)).not.toContain('./lib')
251 expect(modules.reference).not.toMatch(/\bload\b/)
252 expect(importedNames(modules['virtual component']!, './lib')).toEqual([
253 'lib',
254 ])
255 await expectValidModules(modules)
256 },
257 )
258​
259 // Source: Next.js ssg/getStaticProps/should-support-class-exports
260 it('moves a class component and the imports of its static fields into its chunk', async () => {
261 const { modules } =
262 compileRouteModules(`${head}import * as React from 'react'
263import { format } from './format'
264class Page extends React.Component {
265 static title = format('home')
266 render() {
267 return <div>{Page.title}</div>
268 }
270export const Route = createFileRoute('/')({
271 loader: () => 'data',
272 component: Page,
273})
274`)
275 expect(modules.reference).not.toMatch(declarationOf('Page'))
276 expect(importSources(modules.reference!)).not.toContain('./format')
277 expect(modules['virtual component']).toMatch(declarationOf('Page'))
278 expect(importedNames(modules['virtual component']!, './format')).toEqual([
279 'format',
280 ])
281 await expectValidModules(modules)
282 })
283​
284 // Source: Qwik optimizer test.rs should_not_move_over_side_effects,
285 // example_drop_side_effects; Turbopack tree-shaker analyzer/route-kind
286 it.each([
287 {
288 name: 'a compound component member assignment',
289 setup: `function Card({ children }) { return <div>{children}</div> }
290Card.Title = function Title() { return <h1>t</h1> }`,
291 render: '<Card><Card.Title /></Card>',
292 rendered: '<div><h1>t</h1></div>',
293 },
294 {
295 name: 'a registry filled by a top-level call',
296 setup: `const registry = new Map()
297registry.set('a', 'A')`,
298 render: `<p>{registry.get('a')}</p>`,
299 rendered: '<p>A</p>',
300 },
301 {
302 name: 'a compiled enum initializing a var',
303 setup: `var Kind: any
304;(function (Kind: any) {
305 Kind['A'] = 'a'
306})(Kind || (Kind = {}))`,
307 render: '<p>{Kind.A}</p>',
308 rendered: '<p>a</p>',
309 },
310 ])(
311 'renders a split component that relies on $name',
312 async ({ setup, render, rendered }) => {
313 const { modules } = compileRouteModules(`${head}${setup}
314export const Route = createFileRoute('/')({
315 component: () => ${render},
316})
317`)
318 await expectValidModules(modules)
319 expect(await renderSplitComponent(modules)).toBe(rendered)
320 },
321 )
322​
323 // Source: React Compiler hook-ref-callback.js and
324 // dont-memoize-primitive-function-call-non-escaping.js: a function shared by
325 // the loader and the split component declares a local it never reads.
326 it.each([
327 { name: 'a call', initializer: 'track(id)' },
328 { name: 'an optional call', initializer: 'track?.(id)' },
329 ])(
330 'keeps an unused local initialized by $name in a shared function',
331 async ({ initializer }) => {
332 const { modules } =
333 compileRouteModules(`${head}import { track } from './track'
334function useShared(id) {
335 const unused = ${initializer}
336 return id
338export const Route = createFileRoute('/')({
339 loader: () => useShared('loader'),
340 component: () => <p>{useShared('component')}</p>,
341})
342`)
343 const calls: Array<string> = []
344 const shared = await evaluateModule(modules.shared!, {
345 './track': { track: (label: string) => calls.push(label) },
346 })
347 expect(shared.useShared!('render')).toBe('render')
348 expect(calls).toEqual(['render'])
349 },
350 )
351​
352 // Source: babel-dead-code-elimination dead-code-elimination.test.ts "object
353 // pattern" > "within function param"
354 it('keeps empty destructuring parameters of helpers moved into the chunk', async () => {
355 const { modules } =
356 compileRouteModules(`${head}function f(a: any, {}: any) { return a }
357const g = (a: any, []: any) => a
358export const Route = createFileRoute('/')({
359 loader: () => 'data',
360 component: () => <p>{f.length}{g.length}</p>,
361})
362`)
363 const chunk = await evaluateModule(modules['virtual component']!)
364 expect(chunk.component!()).toBe('<p>22</p>')
365 })
366​
367 // Source: React Router remove-exports-test.ts "iife with dependencies"
368 it('moves a component created by an IIFE with its dependencies and shares the helper the loader uses too', async () => {
369 const { modules, sharedBindings } =
370 compileRouteModules(`${head}import { removedLib } from 'removed-lib'
371import { keptLib } from 'kept-lib'
372import { sharedLib } from 'shared-lib'
373const sharedUtil = (value?: unknown) => sharedLib(value)
374const removedUtil = () => sharedUtil(removedLib())
375const keptUtil = () => sharedUtil(keptLib())
376const Page = (() => {
377 const message = removedUtil()
378 return () => <div>{String(message)}</div>
379})()
380export const Route = createFileRoute('/')({
381 loader: () => keptUtil(),
382 component: Page,
383})
384`)
385 expect(sharedBindings).toEqual(['sharedUtil'])
386 expect(importSources(modules.reference!)).toEqual([
387 '@tanstack/react-router',
388 'kept-lib',
389 'route.tsx?tsr-shared=1',
390 ])
391 expect(modules.reference).not.toContain('removedUtil')
392 expect(importSources(modules['virtual component']!)).toEqual([
393 'removed-lib',
394 'route.tsx?tsr-shared=1',
395 ])
396 expect(modules['virtual component']).toMatch(declarationOf('Page'))
397 expect(importSources(modules.shared!)).toEqual(['shared-lib'])
398 await expectValidModules(modules)
399 })
400​
401 // Source: React Router route-chunks-test.ts "isolated exported variable
402 // declarations sharing an export statement"; Next.js
403 // ssg/getStaticProps/should-remove-re-exported-variable-declarations-safe
404 it.each([
405 {
406 name: 'plain declarators',
407 declarations: `const Page = () => <div>{chunkMessage}</div>,
408 main = mainMessage`,
409 },
410 {
411 name: 'destructured declarators',
412 declarations: `const { Page } = { Page: () => <div>{chunkMessage}</div> },
413 { main } = { main: mainMessage }`,
414 },
415 ])(
416 'gives each of the $name of one statement to the module that reads it',
417 async ({ declarations }) => {
418 const { modules, sharedBindings } =
419 compileRouteModules(`${head}import { chunkMessage, mainMessage } from './messages'
420${declarations}
421export const Route = createFileRoute('/')({
422 loader: () => main,
423 component: Page,
424})
425`)
426 expect(sharedBindings).toEqual([])
427 expect(importedNames(modules.reference!, './messages')).toEqual([
428 'mainMessage',
429 ])
430 expect(modules.reference).not.toMatch(/\bPage\b/)
431 expect(
432 importedNames(modules['virtual component']!, './messages'),
433 ).toEqual(['chunkMessage'])
434 expect(modules['virtual component']).not.toMatch(/\bmain\b/)
435 await expectValidModules(modules)
436 },
437 )
438​
439 // Source: React Router route-chunks-test.ts "exported variable declarations
440 // sharing an export statement"
441 it('shares a declarator that a sibling declarator reads', async () => {
442 const { modules, sharedBindings } =
443 compileRouteModules(`${head}import { sharedMessage } from './messages'
444const Page = () => <div>{sharedMessage}</div>,
445 Preview = Page
446export const Route = createFileRoute('/')({
447 loader: () => Preview.name,
448 component: Page,
449})
450`)
451 expect(sharedBindings).toEqual(['Page'])
452 expect(modules.shared).toMatch(declarationOf('Page'))
453 expect(modules.reference).toMatch(declarationOf('Preview'))
454 expect(importedNames(modules.reference!, sharedModule)).toEqual(['Page'])
455 expect(modules.reference).not.toMatch(declarationOf('Page'))
456 expect(modules['virtual component']).not.toMatch(declarationOf('Page'))
457 await expectValidModules(modules)
458 })
459})
460​
461describe('var declarations nested in top-level statements', () => {
462 it.each([
463 {
464 name: 'a for loop head',
465 setup: 'for (var value = 0; value < 3; value++) {}',
466 },
467 { name: 'a for-of head', setup: "for (var value of ['a']) {}" },
468 {
469 name: 'an if block',
470 setup: "if (typeof window === 'undefined') { var value = 'server' }",
471 },
472 ])(
473 'stay bound in every module when $name declares a binding the loader and the component read',
474 async ({ setup }) => {
475 const { modules } = compileRouteModules(`${head}${setup}
476export const Route = createFileRoute('/')({
477 loader: () => value,
478 component: () => <div>{value}</div>,
479})
480`)
481 // Known limitation: the statement runs in both modules instead of once
482 // in the shared module; only check that each module binds `value`.
483 for (const name of ['reference', 'virtual component']) {
484 expect(binds(modules[name]!, 'value'), `${name} binds value`).toBe(true)
485 }
486 await expectValidModules(modules)
487 },
488 )
489​
490 it('stay bound in the reference module when exported and read by the component', async () => {
491 const { modules } =
492 compileRouteModules(`${head}if (typeof window === 'undefined') { var flag = 'server' }
493export { flag }
494export const Route = createFileRoute('/')({
495 component: () => <div>{flag}</div>,
496})
497`)
498 expect(binds(modules.reference!, 'flag')).toBe(true)
499 await expectValidModules(modules)
500 })
501​
502 // Source: babel-dead-code-elimination dead-code-elimination.test.ts "variable"
503 // (var bindings declared inside nested statements)
504 it('follow the only option that reads them', async () => {
505 const { modules } =
506 compileRouteModules(`${head}import { compute, connect } from './lib'
507if (typeof window !== 'undefined') {
508 var flag = compute()
510for (var index = 0; index < 3; index++) {}
512 var block = connect()
514export const Route = createFileRoute('/')({
515 loader: () => block,
516 component: () => <p>{String(flag)}{index}</p>,
517})
518`)
519 expect(modules.reference).not.toContain('compute()')
520 expect(modules.reference).toMatch(declarationOf('block'))
521 const chunk = modules['virtual component']!
522 expect(chunk).toMatch(declarationOf('flag'))
523 expect(chunk).toMatch(declarationOf('index'))
524 expect(chunk).not.toContain('connect()')
525 await expectValidModules(modules)
526 })
527})
528​
529describe('robustness', () => {
530 it('compiles a route with a long method chain', async () => {
531 // Builder APIs (schemas, query builders) produce deep left-nested calls
532 const chain = Array.from({ length: 200 }, (_, i) => `.add(${i})`).join('')
533 const { modules } =
534 compileRouteModules(`${head}import { builder } from './builder'
535const schema = builder()${chain}
536export const Route = createFileRoute('/')({
537 loader: () => schema,
538 component: () => <div>{String(schema)}</div>,
539})
540`)
541 expect(modules.shared).toContain('.add(199)')
542 await expectValidModules(modules)
543 })
544})