Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-routes-compile.md
Original file line number Diff line number Diff line change
@@ -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.
34 changes: 19 additions & 15 deletions packages/router-plugin/src/core/code-splitter/compilers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
const ast = parseAst(opts)

export function computeSharedBindings(
opts: {
code: string
filename?: string
codeSplitGroupings: CodeSplitGroupings
},
ast = parseAst(opts),
): Set<string> {
// 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
Expand Down Expand Up @@ -365,10 +366,10 @@ export function compileCodeSplitReferenceRoute(
opts: ParseAstOptions &
CompileCodeSplitReferenceRouteOptions & {
compilerPlugins?: Array<CodeSplitCompilerPlugin>
sourceMaps?: boolean
},
ast = parseAst(opts),
): GeneratorResult | null {
const ast = parseAst(opts)

const refIdents = findReferencedIdentifiers(ast)

const knownExportedIdents = new Set<string>()
Expand Down Expand Up @@ -857,7 +858,7 @@ export function compileCodeSplitReferenceRoute(
}

const result = generateFromAst(ast, {
sourceMaps: true,
sourceMaps: opts.sourceMaps ?? true,
sourceFileName: opts.filename,
filename: opts.filename,
})
Expand All @@ -880,6 +881,7 @@ export function compileCodeSplitVirtualRoute(
filename: string
sharedBindings?: Set<string>
compilerPlugins?: Array<CodeSplitCompilerPlugin>
sourceMaps?: boolean
},
): GeneratorResult {
const ast = parseAst(opts)
Expand Down Expand Up @@ -1284,7 +1286,7 @@ export function compileCodeSplitVirtualRoute(
}

const result = generateFromAst(ast, {
sourceMaps: true,
sourceMaps: opts.sourceMaps ?? true,
sourceFileName: opts.filename,
filename: opts.filename,
})
Expand All @@ -1306,6 +1308,7 @@ export function compileCodeSplitSharedRoute(
opts: ParseAstOptions & {
sharedBindings: Set<string>
filename: string
sourceMaps?: boolean
},
): GeneratorResult {
const ast = parseAst(opts)
Expand Down Expand Up @@ -1375,7 +1378,7 @@ export function compileCodeSplitSharedRoute(
}

const result = generateFromAst(ast, {
sourceMaps: true,
sourceMaps: opts.sourceMaps ?? true,
sourceFileName: opts.filename,
filename: opts.filename,
})
Expand All @@ -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),
Comment thread
LadyBluenotes marked this conversation as resolved.
Resolved
): {
groupings: CodeSplitGroupings | undefined
} {
const ast = parseAst(opts)

let codeSplitGroupings: CodeSplitGroupings | undefined = undefined

babel.traverse(ast, {
Expand Down
79 changes: 53 additions & 26 deletions packages/router-plugin/src/core/router-code-splitter-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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'
Expand Down Expand Up @@ -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 | (() => Config)> | undefined = {},
routerPluginContext: RouterPluginContext,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand All @@ -214,6 +233,7 @@ export function createRouterCodeSplitterPlugin(
const handleCompilingVirtualFile = (
code: string,
id: string,
sourceMaps: boolean,
): UnpluginTransformResult => {
if (debug) console.info('Splitting Route: ', id)

Expand All @@ -237,6 +257,7 @@ export function createRouterCodeSplitterPlugin(
const resolvedSharedBindings = sharedBindingsMap.get(baseId)

const result = compileCodeSplitVirtualRoute({
sourceMaps,
code,
filename: id,
splitTargets: grouping,
Expand Down Expand Up @@ -276,6 +297,7 @@ export function createRouterCodeSplitterPlugin(
code,
normalizedId,
generatorFileInfo,
shouldGenerateSourceMaps(this),
)
}

Expand Down Expand Up @@ -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),
)
},
},

Expand Down Expand Up @@ -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,
Expand Down
13 changes: 11 additions & 2 deletions packages/router-plugin/tests/code-splitter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
compileCodeSplitSharedRoute,
compileCodeSplitVirtualRoute,
computeSharedBindings,
detectCodeSplitGroupingsFromRoute,
expandDestructuredDeclarations,
expandSharedDestructuredDeclarators,
expandTransitively,
Expand Down Expand Up @@ -77,7 +78,7 @@ describe('code-splitter works', () => {
codeSplitGroupings: grouping,
})

const compileResult = compileCodeSplitReferenceRoute({
const options = {
code,
filename,
id: filename,
Expand All @@ -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),
Expand Down
Loading
Loading