From 23119407a3bf4acb056b21a9773e93d2ec4c7c46 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 6 Sep 2026 14:50:05 -0700 Subject: [PATCH 1/3] perf(router-plugin): avoid redundant compiler work --- .changeset/quiet-routes-compile.md | 5 + .../src/core/code-splitter/compilers.ts | 34 ++--- .../src/core/router-code-splitter-plugin.ts | 79 ++++++++---- .../router-plugin/tests/code-splitter.test.ts | 13 +- .../router-plugin/tests/compiler-work.test.ts | 120 ++++++++++++++++++ 5 files changed, 208 insertions(+), 43 deletions(-) create mode 100644 .changeset/quiet-routes-compile.md create mode 100644 packages/router-plugin/tests/compiler-work.test.ts diff --git a/.changeset/quiet-routes-compile.md b/.changeset/quiet-routes-compile.md new file mode 100644 index 00000000000..023475e1ff1 --- /dev/null +++ b/.changeset/quiet-routes-compile.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-plugin': patch +--- + +Reuse the route AST during reference compilation and skip source maps discarded by the Webpack and Rspack adapters. diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 89cdae41add..3b7d428f538 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -148,13 +148,14 @@ const allCreateRouteFns = [ * AND at least one non-split property. Only locally-declared module-level * bindings are candidates (not imports — bundlers dedupe those). */ -export function computeSharedBindings(opts: { - code: string - filename?: string - codeSplitGroupings: CodeSplitGroupings -}): Set { - const ast = parseAst(opts) - +export function computeSharedBindings( + opts: { + code: string + filename?: string + codeSplitGroupings: CodeSplitGroupings + }, + ast = parseAst(opts), +): Set { // Early bailout: collect all module-level locally-declared binding names. // This is a cheap loop over program.body (no traversal). If the file has // no local bindings (aside from `Route`), nothing can be shared — skip @@ -365,10 +366,10 @@ export function compileCodeSplitReferenceRoute( opts: ParseAstOptions & CompileCodeSplitReferenceRouteOptions & { compilerPlugins?: Array + sourceMaps?: boolean }, + ast = parseAst(opts), ): GeneratorResult | null { - const ast = parseAst(opts) - const refIdents = findReferencedIdentifiers(ast) const knownExportedIdents = new Set() @@ -857,7 +858,7 @@ export function compileCodeSplitReferenceRoute( } const result = generateFromAst(ast, { - sourceMaps: true, + sourceMaps: opts.sourceMaps ?? true, sourceFileName: opts.filename, filename: opts.filename, }) @@ -880,6 +881,7 @@ export function compileCodeSplitVirtualRoute( filename: string sharedBindings?: Set compilerPlugins?: Array + sourceMaps?: boolean }, ): GeneratorResult { const ast = parseAst(opts) @@ -1284,7 +1286,7 @@ export function compileCodeSplitVirtualRoute( } const result = generateFromAst(ast, { - sourceMaps: true, + sourceMaps: opts.sourceMaps ?? true, sourceFileName: opts.filename, filename: opts.filename, }) @@ -1306,6 +1308,7 @@ export function compileCodeSplitSharedRoute( opts: ParseAstOptions & { sharedBindings: Set filename: string + sourceMaps?: boolean }, ): GeneratorResult { const ast = parseAst(opts) @@ -1375,7 +1378,7 @@ export function compileCodeSplitSharedRoute( } const result = generateFromAst(ast, { - sourceMaps: true, + sourceMaps: opts.sourceMaps ?? true, sourceFileName: opts.filename, filename: opts.filename, }) @@ -1392,11 +1395,12 @@ export function compileCodeSplitSharedRoute( * This function should read get the options from by searching for the key `codeSplitGroupings` * on createFileRoute and return it's values if it exists, else return undefined */ -export function detectCodeSplitGroupingsFromRoute(opts: ParseAstOptions): { +export function detectCodeSplitGroupingsFromRoute( + opts: ParseAstOptions, + ast = parseAst(opts), +): { groupings: CodeSplitGroupings | undefined } { - const ast = parseAst(opts) - let codeSplitGroupings: CodeSplitGroupings | undefined = undefined babel.traverse(ast, { diff --git a/packages/router-plugin/src/core/router-code-splitter-plugin.ts b/packages/router-plugin/src/core/router-code-splitter-plugin.ts index f1f75d4f3c1..25a695e7721 100644 --- a/packages/router-plugin/src/core/router-code-splitter-plugin.ts +++ b/packages/router-plugin/src/core/router-code-splitter-plugin.ts @@ -4,7 +4,7 @@ */ import { fileURLToPath, pathToFileURL } from 'node:url' -import { decodeIdentifier, logDiff } from '@tanstack/router-utils' +import { decodeIdentifier, logDiff, parseAst } from '@tanstack/router-utils' import { getConfig, splitGroupingsSchema } from './config' import { compileCodeSplitReferenceRoute, @@ -28,6 +28,7 @@ import type { CodeSplitCompilerPlugin } from './code-splitter/plugins' import type { Config, HmrStyle } from './config' import type { RouterPluginContext } from './router-plugin-context' import type { + UnpluginBuildContext, UnpluginFactory, TransformResult as UnpluginTransformResult, } from 'unplugin' @@ -78,6 +79,18 @@ const TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record< ], } +function shouldGenerateSourceMaps(context: UnpluginBuildContext): boolean { + const nativeContext = context.getNativeBuildContext?.() + if ( + nativeContext?.framework === 'webpack' || + nativeContext?.framework === 'rspack' + ) { + // These unplugin adapters discard generated maps when no input map exists. + return nativeContext.inputSourceMap != null + } + return true +} + export function createRouterCodeSplitterPlugin( options: Partial Config)> | undefined = {}, routerPluginContext: RouterPluginContext, @@ -131,13 +144,16 @@ export function createRouterCodeSplitterPlugin( code: string, id: string, generatorNodeInfo: GetRoutesByFileMapResultValue, + sourceMaps: boolean, ): UnpluginTransformResult => { if (debug) console.info('Compiling Route: ', id) - const fromCode = detectCodeSplitGroupingsFromRoute({ - code, - filename: id, - }) + // Analyze the original AST before the reference compiler mutates it. + const ast = parseAst({ code, filename: id }) + const fromCode = detectCodeSplitGroupingsFromRoute( + { code, filename: id }, + ast, + ) if (fromCode.groupings !== undefined) { const res = splitGroupingsSchema.safeParse(fromCode.groupings) @@ -169,32 +185,35 @@ export function createRouterCodeSplitterPlugin( fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings() // Compute shared bindings before compiling the reference route - const sharedBindings = computeSharedBindings({ - code, - filename: id, - codeSplitGroupings: splitGroupings, - }) + const sharedBindings = computeSharedBindings( + { code, filename: id, codeSplitGroupings: splitGroupings }, + ast, + ) if (sharedBindings.size > 0) { sharedBindingsMap.set(id, sharedBindings) } else { sharedBindingsMap.delete(id) } - const compiledReferenceRoute = compileCodeSplitReferenceRoute({ - code, - codeSplitGroupings: splitGroupings, - targetFramework: userConfig.target, - filename: id, - id, - deleteNodes: userConfig.codeSplittingOptions?.deleteNodes - ? new Set(userConfig.codeSplittingOptions.deleteNodes) - : undefined, - addHmr, - hmrStyle, - hmrRouteId: generatorNodeInfo.routeId, - sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined, - compilerPlugins, - }) + const compiledReferenceRoute = compileCodeSplitReferenceRoute( + { + sourceMaps, + code, + codeSplitGroupings: splitGroupings, + targetFramework: userConfig.target, + filename: id, + id, + deleteNodes: userConfig.codeSplittingOptions?.deleteNodes + ? new Set(userConfig.codeSplittingOptions.deleteNodes) + : undefined, + addHmr, + hmrStyle, + hmrRouteId: generatorNodeInfo.routeId, + sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined, + compilerPlugins, + }, + ast, + ) if (compiledReferenceRoute === null) { if (debug) { @@ -215,6 +234,7 @@ export function createRouterCodeSplitterPlugin( const handleCompilingVirtualFile = ( code: string, id: string, + sourceMaps: boolean, ): UnpluginTransformResult => { if (debug) console.info('Splitting Route: ', id) @@ -238,6 +258,7 @@ export function createRouterCodeSplitterPlugin( const resolvedSharedBindings = sharedBindingsMap.get(baseId) const result = compileCodeSplitVirtualRoute({ + sourceMaps, code, filename: id, splitTargets: grouping, @@ -278,6 +299,7 @@ export function createRouterCodeSplitterPlugin( code, normalizedId, generatorFileInfo, + shouldGenerateSourceMaps(this), ) } @@ -355,7 +377,11 @@ export function createRouterCodeSplitterPlugin( const url = pathToFileURL(id) url.searchParams.delete('v') const normalizedId = normalizePath(fileURLToPath(url)) - return handleCompilingVirtualFile(code, normalizedId) + return handleCompilingVirtualFile( + code, + normalizedId, + shouldGenerateSourceMaps(this), + ) }, }, @@ -390,6 +416,7 @@ export function createRouterCodeSplitterPlugin( if (debug) console.info('Compiling Shared Module: ', id) const result = compileCodeSplitSharedRoute({ + sourceMaps: shouldGenerateSourceMaps(this), code, sharedBindings, filename: normalizedId, diff --git a/packages/router-plugin/tests/code-splitter.test.ts b/packages/router-plugin/tests/code-splitter.test.ts index 967f102e4d4..570cabda9ad 100644 --- a/packages/router-plugin/tests/code-splitter.test.ts +++ b/packages/router-plugin/tests/code-splitter.test.ts @@ -13,6 +13,7 @@ import { compileCodeSplitSharedRoute, compileCodeSplitVirtualRoute, computeSharedBindings, + detectCodeSplitGroupingsFromRoute, expandDestructuredDeclarations, expandSharedDestructuredDeclarators, expandTransitively, @@ -76,7 +77,7 @@ describe('code-splitter works', () => { codeSplitGroupings: grouping, }) - const compileResult = compileCodeSplitReferenceRoute({ + const options = { code, filename, id: filename, @@ -85,7 +86,15 @@ describe('code-splitter works', () => { targetFramework: framework, sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined, - }) + } + const compileResult = compileCodeSplitReferenceRoute(options) + + const ast = parseAst({ code, filename }) + detectCodeSplitGroupingsFromRoute({ code, filename }, ast) + expect(computeSharedBindings(options, ast)).toEqual(sharedBindings) + const reusedAstResult = compileCodeSplitReferenceRoute(options, ast) + expect(reusedAstResult?.code).toEqual(compileResult?.code) + expect(reusedAstResult?.map).toEqual(compileResult?.map) await expect(compileResult?.code || code).toMatchFileSnapshot( path.join(dirs.snapshots, groupName, filename), diff --git a/packages/router-plugin/tests/compiler-work.test.ts b/packages/router-plugin/tests/compiler-work.test.ts new file mode 100644 index 00000000000..2eb52a54218 --- /dev/null +++ b/packages/router-plugin/tests/compiler-work.test.ts @@ -0,0 +1,120 @@ +import { readFile } from 'node:fs/promises' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { parseAst } from '@tanstack/router-utils' +import { createRouterCodeSplitterPlugin } from '../src/core/router-code-splitter-plugin' +import { createRouterPluginContext } from '../src/core/router-plugin-context' +import type { UnpluginBuildContext, UnpluginOptions } from 'unplugin' + +vi.mock('@tanstack/router-utils', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, parseAst: vi.fn(actual.parseAst) } +}) + +const filename = path.resolve('src/routes/todos.tsx') + +async function createPlugins() { + const context = createRouterPluginContext() + context.routesByFile.set(filename, { routeId: '/todos' }) + const plugins = createRouterCodeSplitterPlugin( + { target: 'react', autoCodeSplitting: true }, + context, + ) as Array + const hook = plugins[0]!.vite!.configResolved! + const config = { + root: process.cwd(), + command: 'serve', + plugins: [], + } as never + if (typeof hook === 'function') { + await hook.call({} as never, config) + } else { + await hook.handler.call({} as never, config) + } + return plugins +} + +async function transform( + plugin: UnpluginOptions, + code: string, + id = filename, + context: Partial = {}, +) { + const hook = plugin.transform! + if (typeof hook === 'function') { + throw new Error('Expected object transform') + } + const result = await hook.handler.call(context as never, code, id) + if (typeof result === 'string') { + throw new Error('Expected compiler result') + } + return result +} + +function fixture(name: string) { + return readFile( + path.join(__dirname, 'code-splitter/test-files/react', name), + 'utf8', + ) +} + +describe('reference transform parsing', () => { + it.each(['shared-variable.tsx', 'inline.tsx', 'useStateDestructure.tsx'])( + 'parses %s once per invocation, including repeated and changed source', + async (name) => { + const [reference] = await createPlugins() + const code = await fixture(name) + const updatedCode = code + '\nexport const updated = true' + for (const source of [code, code, updatedCode]) { + vi.mocked(parseAst).mockClear() + const result = await transform(reference!, source) + expect(parseAst).toHaveBeenCalledTimes(1) + const [freshReference] = await createPlugins() + const freshResult = await transform(freshReference!, source) + expect(result).toEqual(freshResult) + } + }, + ) +}) + +describe('compiler source maps', () => { + it.each(['webpack', 'rspack'] as const)( + '%s skips discarded maps and retains maps with incoming source maps', + async (framework) => { + const plugins = await createPlugins() + const code = await fixture('shared-variable.tsx') + for (const [index, suffix] of [ + '', + '?tsr-split=component', + '?tsr-shared=1', + ].entries()) { + const plugin = plugins[index]! + const id = filename + suffix + const baseline = await transform(plugin, code, id) + expect(baseline).toBeTruthy() + expect(baseline!.map).toMatchObject({ + sources: [id], + sourcesContent: [code], + mappings: expect.any(String), + }) + for (const inputSourceMap of [undefined, null, baseline!.map]) { + const result = await transform(plugin, code, id, { + getNativeBuildContext: () => + ({ + framework, + inputSourceMap, + }) as ReturnType< + NonNullable + >, + }) + expect(result!.code).toBe(baseline!.code) + if (inputSourceMap == null) { + expect(result!.map).toBeNull() + } else { + expect(result!.map).toEqual(baseline!.map) + } + } + } + }, + ) +}) From 411148590501fbf1f65564f572de8f39e38bd510 Mon Sep 17 00:00:00 2001 From: Sarah Gerrard Date: Mon, 7 Sep 2026 15:18:26 -0700 Subject: [PATCH 2/3] test: assert compiler output instead of parse counts --- .../router-plugin/tests/compiler-work.test.ts | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/packages/router-plugin/tests/compiler-work.test.ts b/packages/router-plugin/tests/compiler-work.test.ts index 2eb52a54218..5a6d081109f 100644 --- a/packages/router-plugin/tests/compiler-work.test.ts +++ b/packages/router-plugin/tests/compiler-work.test.ts @@ -1,17 +1,12 @@ import { readFile } from 'node:fs/promises' import path from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { parseAst } from '@tanstack/router-utils' +import { describe, expect, it } from 'vitest' import { createRouterCodeSplitterPlugin } from '../src/core/router-code-splitter-plugin' import { createRouterPluginContext } from '../src/core/router-plugin-context' +import { normalizePath } from '../src/core/utils' import type { UnpluginBuildContext, UnpluginOptions } from 'unplugin' -vi.mock('@tanstack/router-utils', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, parseAst: vi.fn(actual.parseAst) } -}) - -const filename = path.resolve('src/routes/todos.tsx') +const filename = normalizePath(path.resolve('src/routes/todos.tsx')) async function createPlugins() { const context = createRouterPluginContext() @@ -58,17 +53,16 @@ function fixture(name: string) { ) } -describe('reference transform parsing', () => { +describe('reference transform output', () => { it.each(['shared-variable.tsx', 'inline.tsx', 'useStateDestructure.tsx'])( - 'parses %s once per invocation, including repeated and changed source', + 'transforms repeated and changed %s source consistently', async (name) => { const [reference] = await createPlugins() const code = await fixture(name) const updatedCode = code + '\nexport const updated = true' for (const source of [code, code, updatedCode]) { - vi.mocked(parseAst).mockClear() const result = await transform(reference!, source) - expect(parseAst).toHaveBeenCalledTimes(1) + expect(result?.code).toContain('createFileRoute(') const [freshReference] = await createPlugins() const freshResult = await transform(freshReference!, source) expect(result).toEqual(freshResult) @@ -79,7 +73,7 @@ describe('reference transform parsing', () => { describe('compiler source maps', () => { it.each(['webpack', 'rspack'] as const)( - '%s skips discarded maps and retains maps with incoming source maps', + '%s preserves transformed code and incoming source maps', async (framework) => { const plugins = await createPlugins() const code = await fixture('shared-variable.tsx') @@ -108,9 +102,7 @@ describe('compiler source maps', () => { >, }) expect(result!.code).toBe(baseline!.code) - if (inputSourceMap == null) { - expect(result!.map).toBeNull() - } else { + if (inputSourceMap != null) { expect(result!.map).toEqual(baseline!.map) } } From bdaee7b0ad14aa2b9c5e23653e8aa517e23d05ed Mon Sep 17 00:00:00 2001 From: Sarah Gerrard Date: Mon, 7 Sep 2026 15:44:20 -0700 Subject: [PATCH 3/3] test(router-plugin): assert missing source maps --- packages/router-plugin/tests/compiler-work.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/router-plugin/tests/compiler-work.test.ts b/packages/router-plugin/tests/compiler-work.test.ts index 5a6d081109f..babd2f264c8 100644 --- a/packages/router-plugin/tests/compiler-work.test.ts +++ b/packages/router-plugin/tests/compiler-work.test.ts @@ -104,6 +104,8 @@ describe('compiler source maps', () => { expect(result!.code).toBe(baseline!.code) if (inputSourceMap != null) { expect(result!.map).toEqual(baseline!.map) + } else { + expect(result!.map).toBeNull() } } }