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 596bd6e0120..44ab65d88ef 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, @@ -27,6 +27,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' @@ -77,6 +78,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, @@ -130,13 +143,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) @@ -168,32 +184,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) { @@ -214,6 +233,7 @@ export function createRouterCodeSplitterPlugin( const handleCompilingVirtualFile = ( code: string, id: string, + sourceMaps: boolean, ): UnpluginTransformResult => { if (debug) console.info('Splitting Route: ', id) @@ -237,6 +257,7 @@ export function createRouterCodeSplitterPlugin( const resolvedSharedBindings = sharedBindingsMap.get(baseId) const result = compileCodeSplitVirtualRoute({ + sourceMaps, code, filename: id, splitTargets: grouping, @@ -276,6 +297,7 @@ export function createRouterCodeSplitterPlugin( code, normalizedId, generatorFileInfo, + shouldGenerateSourceMaps(this), ) } @@ -353,7 +375,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), + ) }, }, @@ -388,6 +414,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 96807e4d427..956e9e5149c 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, @@ -77,7 +78,7 @@ describe('code-splitter works', () => { codeSplitGroupings: grouping, }) - const compileResult = compileCodeSplitReferenceRoute({ + const options = { code, filename, id: filename, @@ -86,7 +87,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( await formatSnapshot(compileResult?.code || code, 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..babd2f264c8 --- /dev/null +++ b/packages/router-plugin/tests/compiler-work.test.ts @@ -0,0 +1,114 @@ +import { readFile } from 'node:fs/promises' +import path from 'node:path' +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' + +const filename = normalizePath(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 output', () => { + it.each(['shared-variable.tsx', 'inline.tsx', 'useStateDestructure.tsx'])( + '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]) { + const result = await transform(reference!, source) + expect(result?.code).toContain('createFileRoute(') + 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 preserves transformed code and 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).toEqual(baseline!.map) + } else { + expect(result!.map).toBeNull() + } + } + } + }, + ) +})