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/quick-dingos-decide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/router-plugin': patch
---

Improve route code-splitting build performance by parsing each reference route once for grouping detection, shared-binding analysis, and compilation.
25 changes: 14 additions & 11 deletions packages/router-plugin/ARCHITECTURE-CODE-SPLITTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ flowchart TB
end

subgraph "Plugin 1: compile-reference-file"
P1["Transform about.tsx<br/>• computeSharedBindings()<br/>• compileCodeSplitReferenceRoute()"]
P1["Transform about.tsx<br/>• computeSharedBindingsFromAst()<br/>• compileCodeSplitReferenceRouteFromAst()"]
end

subgraph "Plugin 2: compile-virtual-file"
Expand Down Expand Up @@ -126,9 +126,12 @@ Excludes file IDs that include `tsr-split` or `tsr-shared`.

**What it does:**

1. Detects per-route `codeSplitGroupings` if specified inline
2. Calls `computeSharedBindings()` and caches the result in `sharedBindingsMap`
3. Calls `compileCodeSplitReferenceRoute()` which:
1. Parses the reference source once and detects per-route `codeSplitGroupings`
if specified inline
2. Calls `computeSharedBindingsFromAst()` and caches the binding names in
`sharedBindingsMap`
3. Passes that same AST to `compileCodeSplitReferenceRouteFromAst()` after both
analyses finish. The compiler mutates the AST, which stays local to this transform:
- Replaces split properties with `lazyRouteComponent()` / `lazyFn()` wrappers
- Injects `import()` expressions pointing to `?tsr-split=<encoded>` URLs
- Removes shared binding declarations, replacing them with
Expand Down Expand Up @@ -285,15 +288,15 @@ size issue.

### The Solution

`computeSharedBindings()` identifies bindings that are referenced by properties
`computeSharedBindingsFromAst()` identifies bindings that are referenced by properties
in 2+ distinct "groups" (where each split grouping index is one group, and all
non-split properties form group `-1`). These bindings are extracted into a
third virtual module (`?tsr-shared=1`) that both the reference module and the
split modules import from, ensuring a single shared instance.

### How `computeSharedBindings()` Works
### How `computeSharedBindingsFromAst()` Works

**Location:** `src/core/code-splitter/compilers.ts` (`computeSharedBindings`)
**Location:** `src/core/code-splitter/compilers.ts` (`computeSharedBindingsFromAst`)

**Algorithm:**

Expand Down Expand Up @@ -415,7 +418,7 @@ imports `cache` (needed by `setCached`) from the shared module.
The three plugins share a closure containing `sharedBindingsMap`:

```
Plugin 1 (reference): computeSharedBindings() → sharedBindingsMap.set(id, bindings)
Plugin 1 (reference): computeSharedBindingsFromAst() → sharedBindingsMap.set(id, bindings)
Plugin 2 (virtual): sharedBindingsMap.get(baseId) → pass to compileCodeSplitVirtualRoute()
Plugin 3 (shared): sharedBindingsMap.get(baseId) → pass to compileCodeSplitSharedRoute()
```
Expand Down Expand Up @@ -609,14 +612,14 @@ transitive dependencies.
6. Run `deadCodeElimination()`
7. Generate output with source maps

### `computeSharedBindings()`
### `computeSharedBindingsFromAst()`

**Purpose:** Analyze a route file to determine which module-level bindings
are referenced by multiple split groups.

See [Shared Bindings System](#shared-bindings-system) for the full algorithm.

### `detectCodeSplitGroupingsFromRoute()`
### `detectCodeSplitGroupingsFromAst()`

**Purpose:** Parse inline `codeSplitGroupings` from route options.

Expand Down Expand Up @@ -849,7 +852,7 @@ it. Bundlers process transforms in plugin array order for a given module ID.

### 9. Imported Bindings Are Never Shared

`computeSharedBindings()` only considers **locally-declared** module-level
`computeSharedBindingsFromAst()` only considers **locally-declared** module-level
bindings. Import statements are handled by the bundler's module system — if
both the reference file and a virtual file import the same external module,
the bundler deduplicates that import automatically. No shared module needed.
Expand Down
47 changes: 26 additions & 21 deletions packages/router-plugin/src/core/code-splitter/compilers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ import type {
CodeSplitCompilerPlugin,
CompileCodeSplitReferenceRouteOptions,
} from './plugins'
import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'
import type {
GeneratorResult,
ParseAstOptions,
ParseAstResult,
} from '@tanstack/router-utils'
import type { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants'
import type { SplitNodeMeta } from './types'

Expand Down Expand Up @@ -147,14 +151,12 @@ const allCreateRouteFns = [
* A binding is "shared" if it is referenced by at least one split property
* AND at least one non-split property. Only locally-declared module-level
* bindings are candidates (not imports — bundlers dedupe those).
* Analyze the original AST before the reference compiler mutates it.
*/
export function computeSharedBindings(opts: {
code: string
filename?: string
codeSplitGroupings: CodeSplitGroupings
}): Set<string> {
const ast = parseAst(opts)

export function computeSharedBindingsFromAst(
ast: t.File,
codeSplitGroupings: CodeSplitGroupings,
): 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 All @@ -173,9 +175,7 @@ export function computeSharedBindings(opts: {
}

function findIndexForSplitNode(str: string) {
return opts.codeSplitGroupings.findIndex((group) =>
group.includes(str as any),
)
return codeSplitGroupings.findIndex((group) => group.includes(str as any))
}

// Find the route options object — needs babel.traverse for scope resolution
Expand Down Expand Up @@ -361,14 +361,22 @@ function removeSharedDeclarations(ast: t.File, sharedBindings: Set<string>) {
})
}

type ReferenceCompilerOptions = ParseAstOptions &
CompileCodeSplitReferenceRouteOptions & {
compilerPlugins?: Array<CodeSplitCompilerPlugin>
}

export function compileCodeSplitReferenceRoute(
opts: ParseAstOptions &
CompileCodeSplitReferenceRouteOptions & {
compilerPlugins?: Array<CodeSplitCompilerPlugin>
},
opts: ReferenceCompilerOptions,
): GeneratorResult | null {
const ast = parseAst(opts)
return compileCodeSplitReferenceRouteFromAst(parseAst(opts), opts)
}

/** Internal compiler: consumes the AST after grouping and shared-binding analysis. */
export function compileCodeSplitReferenceRouteFromAst(
ast: ParseAstResult,
opts: ReferenceCompilerOptions,
): GeneratorResult | null {
const refIdents = findReferencedIdentifiers(ast)

const knownExportedIdents = new Set<string>()
Expand Down Expand Up @@ -1389,14 +1397,11 @@ 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
* Reads inline codeSplitGroupings from the original, unmodified reference AST.
*/
export function detectCodeSplitGroupingsFromRoute(opts: ParseAstOptions): {
export function detectCodeSplitGroupingsFromAst(ast: t.File): {
groupings: CodeSplitGroupings | undefined
} {
const ast = parseAst(opts)

let codeSplitGroupings: CodeSplitGroupings | undefined = undefined

babel.traverse(ast, {
Expand Down
21 changes: 9 additions & 12 deletions packages/router-plugin/src/core/router-code-splitter-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
*/

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,
compileCodeSplitReferenceRouteFromAst,
compileCodeSplitSharedRoute,
compileCodeSplitVirtualRoute,
computeSharedBindings,
detectCodeSplitGroupingsFromRoute,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are those functions still used (outside of tests)? we should not keep them if not used, dont shim them etc.

computeSharedBindingsFromAst,
detectCodeSplitGroupingsFromAst,
} from './code-splitter/compilers'
import { getFrameworkHmrCompilerPlugins } from './code-splitter/plugins/framework-plugins'
import {
Expand Down Expand Up @@ -134,10 +134,11 @@ export function createRouterCodeSplitterPlugin(
): UnpluginTransformResult => {
if (debug) console.info('Compiling Route: ', id)

const fromCode = detectCodeSplitGroupingsFromRoute({
const ast = parseAst({
code,
filename: id,
})
const fromCode = detectCodeSplitGroupingsFromAst(ast)

if (fromCode.groupings !== undefined) {
const res = splitGroupingsSchema.safeParse(fromCode.groupings)
Expand Down Expand Up @@ -168,19 +169,15 @@ export function createRouterCodeSplitterPlugin(
const splitGroupings: CodeSplitGroupings =
fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()

// Compute shared bindings before compiling the reference route
const sharedBindings = computeSharedBindings({
code,
filename: id,
codeSplitGroupings: splitGroupings,
})
// Both analyses must finish before the reference compiler mutates this AST.
const sharedBindings = computeSharedBindingsFromAst(ast, splitGroupings)
if (sharedBindings.size > 0) {
sharedBindingsMap.set(id, sharedBindings)
} else {
sharedBindingsMap.delete(id)
}

const compiledReferenceRoute = compileCodeSplitReferenceRoute({
const compiledReferenceRoute = compileCodeSplitReferenceRouteFromAst(ast, {
code,
codeSplitGroupings: splitGroupings,
targetFramework: userConfig.target,
Expand Down
35 changes: 31 additions & 4 deletions packages/router-plugin/tests/add-hmr.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { readFile, readdir } from 'node:fs/promises'
import path from 'node:path'
import { describe, expect, it } from 'vitest'

import { compileCodeSplitReferenceRoute } from '../src/core/code-splitter/compilers'
import { parseAst } from '@tanstack/router-utils'

import {
compileCodeSplitReferenceRoute,
compileCodeSplitReferenceRouteFromAst,
computeSharedBindingsFromAst,
detectCodeSplitGroupingsFromAst,
} from '../src/core/code-splitter/compilers'
import { defaultCodeSplitGroupings } from '../src/core/constants'
import { getFrameworkHmrCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins'
import { createRouteHmrStatement } from '../src/core/hmr'
Expand All @@ -14,6 +20,27 @@ function getFrameworkDir(framework: string) {
return { files, snapshots }
}

function compileWithRootParity(
opts: Parameters<typeof compileCodeSplitReferenceRoute>[0],
) {
const result = compileCodeSplitReferenceRoute(opts)
if (opts.filename.startsWith('createRootRoute')) {
// Reuse root snapshots for both paths, including WithContext/type arguments
// and the addHmr:false null-result path. Roots must never be extracted.
const ast = parseAst(opts)
expect(detectCodeSplitGroupingsFromAst(ast).groupings).toBeUndefined()
expect(
computeSharedBindingsFromAst(ast, opts.codeSplitGroupings).size,
).toBe(0)
const parsedResult = compileCodeSplitReferenceRouteFromAst(ast, opts)
expect(parsedResult === null).toBe(result === null)
expect(parsedResult?.code).toBe(result?.code)
expect(parsedResult?.map).toEqual(result?.map)
return parsedResult
}
return result
}

describe('add-hmr works', () => {
describe.each(frameworks)('FRAMEWORK=%s', async (framework) => {
const dirs = getFrameworkDir(framework)
Expand All @@ -25,7 +52,7 @@ describe('add-hmr works', () => {
const file = await readFile(path.join(dirs.files, filename))
const code = file.toString()

const compileResult = compileCodeSplitReferenceRoute({
const compileResult = compileWithRootParity({
code,
filename,
id: filename,
Expand All @@ -49,7 +76,7 @@ describe('add-hmr works', () => {
const file = await readFile(path.join(dirs.files, filename))
const code = file.toString()

const compileResult = compileCodeSplitReferenceRoute({
const compileResult = compileWithRootParity({
code,
filename,
id: filename,
Expand Down
Loading
Loading