Open History to see the last commit
1/**
2 * It is important to familiarize yourself with how the code-splitting works in this plugin.
3 * https://github.com/TanStack/router/pull/3355
4 */
5β
6import { fileURLToPath, pathToFileURL } from 'node:url'
7import { decodeIdentifier, logDiff } from '@tanstack/router-utils'
8import { getConfig, splitGroupingsSchema } from './config'
9import {
10 analyzeRouteModule,
11 compileCodeSplitReferenceRoute,
12 compileCodeSplitSharedRoute,
13 compileCodeSplitVirtualRoute,
14 computeSharedBindings,
15 createDuplicateFileRouteMessage,
16 createRouteInFunctionMessage,
17 detectCodeSplitGroupingsFromRoute,
18 getRouteModuleWarnings,
19} from './code-splitter/compilers'
20import { getFrameworkHmrCompilerPlugins } from './code-splitter/plugins/framework-plugins'
21import {
22 defaultCodeSplitGroupings,
23 splitRouteIdentNodes,
24 tsrShared,
25 tsrSplit,
26} from './constants'
27import { debug, normalizePath, routeFactoryCallCodeFilter } from './utils'
28import { createRouterPluginContext } from './router-plugin-context'
29import type { RouteModuleAnalysis } from './code-splitter/compilers'
30import type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'
31import type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'
32import type { CodeSplitCompilerPlugin } from './code-splitter/plugins'
33import type { Config, HmrStyle } from './config'
34import type { RouterPluginContext } from './router-plugin-context'
35import type {
36 UnpluginFactory,
37 TransformResult as UnpluginTransformResult,
38} from 'unplugin'
39β
40const CODE_SPLITTER_PLUGIN_NAME =
41 'tanstack-router:code-splitter:compile-reference-file'
42β
43type TransformationPluginInfo = {
44 pluginNames: Array<string>
45 pkg: string
46 usage: string
47}
48β
49/**
50 * JSX transformation plugins grouped by framework.
51 * These plugins must come AFTER the TanStack Router plugin in the Vite config.
52 */
53const TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<
54 string,
55 Array<TransformationPluginInfo>
56> = {
57 react: [
58 {
59 // Babel-based React plugin
60 pluginNames: ['vite:react-babel', 'vite:react-refresh'],
61 pkg: '@vitejs/plugin-react',
62 usage: 'react()',
63 },
64 {
65 // SWC-based React plugin
66 pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],
67 pkg: '@vitejs/plugin-react-swc',
68 usage: 'reactSwc()',
69 },
70 {
71 // OXC-based React plugin (deprecated but should still be handled)
72 pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],
73 pkg: '@vitejs/plugin-react-oxc',
74 usage: 'reactOxc()',
75 },
76 ],
77 solid: [
78 {
79 pluginNames: ['solid'],
80 pkg: 'vite-plugin-solid',
81 usage: 'solid()',
82 },
83 ],
84}
85β
86export function createRouterCodeSplitterPlugin(
87 options: Partial<Config | (() => Config)> | undefined = {},
88 routerPluginContext: RouterPluginContext,
89): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> {
90 let ROOT: string = process.cwd()
91 let userConfig: Config
92 let addHmr: boolean
93 let hmrStyle: HmrStyle
94 let compilerPlugins: Array<CodeSplitCompilerPlugin>
95 let virtualRouteCompilerPlugins: Array<CodeSplitCompilerPlugin>
96β
97 let isProduction = process.env.NODE_ENV === 'production'
98β
99 function initUserConfig() {
100 if (typeof options === 'function') {
101 userConfig = options()
102 } else {
103 userConfig = getConfig(options, ROOT)
104 }
105β
106 addHmr = (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction
107 hmrStyle = userConfig.plugin?.hmr?.style ?? 'vite'
108 compilerPlugins = [
109 ...(addHmr
110 ? (getFrameworkHmrCompilerPlugins({
111 targetFramework: userConfig.target,
112 hmrStyle,
113 }) ?? [])
114 : []),
115 ...(userConfig.codeSplittingOptions?.compilerPlugins ?? []),
116 ]
117 virtualRouteCompilerPlugins = compilerPlugins.filter(
118 (plugin) => plugin.onVirtualRouteSplitNode,
119 )
120 }
121 // Map from normalized route file path β set of shared binding names.
122 // Populated by the reference compiler, consumed by virtual and shared compilers.
123 const sharedBindingsMap = new Map<string, Set<string>>()
124 // Cache only immutable source analysis; chunk settings and generated output
125 // stay per transform. A bounded cache avoids retaining every route AST.
126 const analyzedRoutes = new Map<
127 string,
128 { code: string; analysis: RouteModuleAnalysis }
129 >()
130 function getRouteAnalysis(code: string, id: string) {
131 const [pathname, query] = id.split('?')
132 const parameters = new URLSearchParams(query)
133 parameters.delete(tsrSplit)
134 parameters.delete(tsrShared)
135 const filename = parameters.size ? `${pathname}?${parameters}` : pathname!
136 const cached = analyzedRoutes.get(filename)
137 if (cached?.code === code) {
138 analyzedRoutes.delete(filename)
139 analyzedRoutes.set(filename, cached)
140 return cached.analysis
141 }
142 const analysis = analyzeRouteModule({ code, filename })
143 analyzedRoutes.delete(filename)
144 analyzedRoutes.set(filename, { code, analysis })
145 if (analyzedRoutes.size > 128) {
146 analyzedRoutes.delete(analyzedRoutes.keys().next().value!)
147 }
148 return analysis
149 }
150β
151 // Warnings already reported: once per message, which names the route file,
152 // so an edit that changes the problem reports it again
153 const reportedWarnings = new Set<string>()
154β
155 const getGlobalCodeSplitGroupings = () => {
156 return (
157 userConfig.codeSplittingOptions?.defaultBehavior ||
158 defaultCodeSplitGroupings
159 )
160 }
161 const getShouldSplitFn = () => {
162 return userConfig.codeSplittingOptions?.splitBehavior
163 }
164β
165 const handleCompilingReferenceFile = (
166 code: string,
167 id: string,
168 generatorNodeInfo: GetRoutesByFileMapResultValue,
169 warn: (message: string) => void,
170 ): UnpluginTransformResult => {
171 if (debug) console.info('Compiling Route: ', id)
172β
173 const duplicateFileRoute = createDuplicateFileRouteMessage(
174 getRouteAnalysis(code, id),
175 id,
176 )
177 if (duplicateFileRoute) {
178 throw new Error(duplicateFileRoute)
179 }
180β
181 const fromCode = detectCodeSplitGroupingsFromRoute({
182 code,
183 filename: id,
184 analysis: getRouteAnalysis(code, id),
185 })
186β
187 if (fromCode.groupings !== undefined) {
188 const res = splitGroupingsSchema.safeParse(fromCode.groupings)
189 if (!res.success) {
190 const message = res.error.issues.map((e) => e.message).join('. ')
191 throw new Error(
192 `The groupings for the route "${id}" are invalid.\n${message}`,
193 )
194 }
195 }
196β
197 const userShouldSplitFn = getShouldSplitFn()
198β
199 const pluginSplitBehavior = userShouldSplitFn?.({
200 routeId: generatorNodeInfo.routeId,
201 }) as CodeSplitGroupings | undefined
202β
203 if (pluginSplitBehavior) {
204 const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)
205 if (!res.success) {
206 const message = res.error.issues.map((e) => e.message).join('. ')
207 throw new Error(
208 `The groupings returned when using \`splitBehavior\` for the route "${id}" are invalid.\n${message}`,
209 )
210 }
211 }
212β
213 const splitGroupings: CodeSplitGroupings =
214 fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()
215β
216 for (const message of getRouteModuleWarnings(
217 getRouteAnalysis(code, id),
218 id,
219 splitGroupings,
220 )) {
221 warn(message)
222 }
223β
224 // Compute shared bindings before compiling the reference route
225 const sharedBindings = computeSharedBindings({
226 code,
227 filename: id,
228 analysis: getRouteAnalysis(code, id),
229 codeSplitGroupings: splitGroupings,
230 })
231 if (sharedBindings.size > 0) {
232 sharedBindingsMap.set(id, sharedBindings)
233 } else {
234 sharedBindingsMap.delete(id)
235 }
236β
237 const compiledReferenceRoute = compileCodeSplitReferenceRoute({
238 code,
239 analysis: getRouteAnalysis(code, id),
240 codeSplitGroupings: splitGroupings,
241 targetFramework: userConfig.target,
242 filename: id,
243 id,
244 deleteNodes: userConfig.codeSplittingOptions?.deleteNodes
245 ? new Set(userConfig.codeSplittingOptions.deleteNodes)
246 : undefined,
247 addHmr,
248 hmrStyle,
249 hmrRouteId: generatorNodeInfo.routeId,
250 sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,
251 compilerPlugins,
252 warn,
253 })
254β
255 if (compiledReferenceRoute === null) {
256 if (debug) {
257 console.info(
258 `No changes made to route "${id}", skipping code-splitting.`,
259 )
260 }
261 return null
262 }
263 if (debug) {
264 logDiff(code, compiledReferenceRoute.code)
265 console.log('Output:\n', compiledReferenceRoute.code + '\n\n')
266 }
267β
268 return compiledReferenceRoute
269 }
270β
271 const handleCompilingVirtualFile = (
272 code: string,
273 id: string,
274 ): UnpluginTransformResult => {
275 if (debug) console.info('Splitting Route: ', id)
276β
277 const [_, ...pathnameParts] = id.split('?')
278β
279 const searchParams = new URLSearchParams(pathnameParts.join('?'))
280 const splitValue = searchParams.get(tsrSplit)
281β
282 if (!splitValue) {
283 throw new Error(
284 `The split value for the virtual route "${id}" was not found.`,
285 )
286 }
287β
288 const rawGrouping = decodeIdentifier(splitValue)
289 const grouping = [...new Set(rawGrouping)].filter((p) =>
290 splitRouteIdentNodes.includes(p as any),
291 ) as Array<SplitRouteIdentNodes>
292β
293 const baseId = id.split('?')[0]!
294 const resolvedSharedBindings = sharedBindingsMap.get(baseId)
295β
296 const result = compileCodeSplitVirtualRoute({
297 code,
298 analysis: getRouteAnalysis(code, id),
299 filename: id,
300 splitTargets: grouping,
301 sharedBindings: resolvedSharedBindings,
302 compilerPlugins: virtualRouteCompilerPlugins,
303 })
304β
305 if (debug) {
306 logDiff(code, result.code)
307 console.log('Output:\n', result.code + '\n\n')
308 }
309β
310 return result
311 }
312β
313 return [
314 {
315 name: 'tanstack-router:code-splitter:compile-reference-file',
316 enforce: 'pre',
317 buildEnd() {
318 analyzedRoutes.clear()
319 },
320β
321 transform: {
322 filter: {
323 id: {
324 exclude: [tsrSplit, tsrShared],
325 // this is necessary for webpack / rspack to avoid matching .html files
326 include: /\.(m|c)?(j|t)sx?$/,
327 },
328 code: {
329 include: routeFactoryCallCodeFilter,
330 },
331 },
332 handler(code, id) {
333 const normalizedId = normalizePath(id)
334 const generatorFileInfo =
335 routerPluginContext.routesByFile.get(normalizedId)
336 if (generatorFileInfo) {
337 const warn = (message: string) => {
338 if (!reportedWarnings.has(message)) {
339 reportedWarnings.add(message)
340 this.warn(message)
341 }
342 }
343 if (getRouteAnalysis(code, normalizedId).routeCreatedInFunction) {
344 warn(createRouteInFunctionMessage(normalizedId))
345 }
346 return handleCompilingReferenceFile(
347 code,
348 normalizedId,
349 generatorFileInfo,
350 warn,
351 )
352 }
353β
354 return null
355 },
356 },
357β
358 vite: {
359 configResolved(config) {
360 isProduction = config.command === 'build'
361 ROOT = config.root
362 initUserConfig()
363β
364 // Validate plugin order - router must come before JSX transformation plugins
365 const routerPluginIndex = config.plugins.findIndex(
366 (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,
367 )
368β
369 if (routerPluginIndex === -1) return
370β
371 const frameworkPlugins =
372 TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]
373 if (!frameworkPlugins) return
374β
375 for (const transformPlugin of frameworkPlugins) {
376 const transformPluginIndex = config.plugins.findIndex((p) =>
377 transformPlugin.pluginNames.includes(p.name),
378 )
379β
380 if (
381 transformPluginIndex !== -1 &&
382 transformPluginIndex < routerPluginIndex
383 ) {
384 throw new Error(
385 `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\n\n` +
386 `The TanStack Router plugin must come BEFORE JSX transformation plugins.\n\n` +
387 `Please update your Vite config:\n\n` +
388 ` plugins: [\n` +
389 ` tanstackRouter(),\n` +
390 ` ${transformPlugin.usage},\n` +
391 ` ]\n`,
392 )
393 }
394 }
395 },
396 applyToEnvironment(environment) {
397 if (userConfig.plugin?.vite?.environmentName) {
398 return userConfig.plugin.vite.environmentName === environment.name
399 }
400 return true
401 },
402 },
403β
404 rspack(compiler) {
405 isProduction = compiler.options.mode === 'production'
406 ROOT = process.cwd()
407 initUserConfig()
408 },
409β
410 webpack(compiler) {
411 isProduction = compiler.options.mode === 'production'
412 ROOT = process.cwd()
413 initUserConfig()
414 },
415 },
416 {
417 name: 'tanstack-router:code-splitter:compile-virtual-file',
418 enforce: 'pre',
419β
420 transform: {
421 filter: {
422 id: /tsr-split/,
423 },
424 handler(code, id) {
425 const url = pathToFileURL(id)
426 url.searchParams.delete('v')
427 const normalizedId = normalizePath(fileURLToPath(url))
428 return handleCompilingVirtualFile(code, normalizedId)
429 },
430 },
431β
432 vite: {
433 applyToEnvironment(environment) {
434 if (userConfig.plugin?.vite?.environmentName) {
435 return userConfig.plugin.vite.environmentName === environment.name
436 }
437 return true
438 },
439 },
440 },
441 {
442 name: 'tanstack-router:code-splitter:compile-shared-file',
443 enforce: 'pre',
444β
445 transform: {
446 filter: {
447 id: /tsr-shared/,
448 },
449 handler(code, id) {
450 const url = pathToFileURL(id)
451 url.searchParams.delete('v')
452 const normalizedId = normalizePath(fileURLToPath(url))
453 const [baseId] = normalizedId.split('?')
454β
455 if (!baseId) return null
456β
457 const sharedBindings = sharedBindingsMap.get(baseId)
458 if (!sharedBindings || sharedBindings.size === 0) return null
459β
460 if (debug) console.info('Compiling Shared Module: ', id)
461β
462 const result = compileCodeSplitSharedRoute({
463 code,
464 analysis: getRouteAnalysis(code, normalizedId),
465 sharedBindings,
466 filename: normalizedId,
467 })
468β
469 if (debug) {
470 logDiff(code, result.code)
471 console.log('Output:\n', result.code + '\n\n')
472 }
473β
474 return result
475 },
476 },
477β
478 vite: {
479 applyToEnvironment(environment) {
480 if (userConfig.plugin?.vite?.environmentName) {
481 return userConfig.plugin.vite.environmentName === environment.name
482 }
483 return true
484 },
485 },
486 },
487 ]
488}
489β
490export const unpluginRouterCodeSplitterFactory: UnpluginFactory<
491 Partial<Config | (() => Config)> | undefined
492> = (options = {}) => {
493 return createRouterCodeSplitterPlugin(options, createRouterPluginContext())
494}