-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcompilers.ts
More file actions
1718 lines (1516 loc) · 60.4 KB
/
Copy pathcompilers.ts
File metadata and controls
1718 lines (1516 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as t from '@babel/types'
import * as babel from '@babel/core'
import * as template from '@babel/template'
import {
buildDeclarationMap,
buildDependencyGraph,
collectIdentifiersFromPattern,
collectLocalBindingsFromStatement,
collectModuleLevelRefsFromNode,
createIdentifier,
deadCodeElimination,
expandDestructuredDeclarations,
expandSharedDestructuredDeclarators,
expandTransitively,
findReferencedIdentifiers,
generateFromAst,
parseAst,
removeBindingsTransitivelyDependingOn,
retainModuleLevelDeclarations,
stripUnreferencedTopLevelExpressionStatements,
unwrapExportedDeclarations,
} from '@tanstack/router-utils'
import { tsrShared, tsrSplit } from '../constants'
import { createRouteHmrStatement } from '../hmr'
import { getObjectPropertyKeyName } from '../utils'
import { getFrameworkOptions } from './framework-options'
import type {
CompileCodeSplitReferenceRouteOptions,
ReferenceRouteCompilerPlugin,
} from './plugins'
import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'
import type { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants'
import type { SplitNodeMeta } from './types'
export {
buildDeclarationMap,
buildDependencyGraph,
collectIdentifiersFromNode,
collectLocalBindingsFromStatement,
collectModuleLevelRefsFromNode,
expandDestructuredDeclarations,
expandSharedDestructuredDeclarators,
expandTransitively,
removeBindingsTransitivelyDependingOn,
} from '@tanstack/router-utils'
export function removeBindingsDependingOnRoute(
bindings: Set<string>,
dependencyGraph: Map<string, Set<string>>,
) {
removeBindingsTransitivelyDependingOn(bindings, dependencyGraph, ['Route'])
}
const SPLIT_NODES_CONFIG = new Map<SplitRouteIdentNodes, SplitNodeMeta>([
[
'loader',
{
routeIdent: 'loader',
localImporterIdent: '$$splitLoaderImporter', // const $$splitLoaderImporter = () => import('...')
splitStrategy: 'lazyFn',
localExporterIdent: 'SplitLoader', // const SplitLoader = ...
exporterIdent: 'loader', // export { SplitLoader as loader }
},
],
[
'component',
{
routeIdent: 'component',
localImporterIdent: '$$splitComponentImporter', // const $$splitComponentImporter = () => import('...')
splitStrategy: 'lazyRouteComponent',
localExporterIdent: 'SplitComponent', // const SplitComponent = ...
exporterIdent: 'component', // export { SplitComponent as component }
},
],
[
'pendingComponent',
{
routeIdent: 'pendingComponent',
localImporterIdent: '$$splitPendingComponentImporter', // const $$splitPendingComponentImporter = () => import('...')
splitStrategy: 'lazyRouteComponent',
localExporterIdent: 'SplitPendingComponent', // const SplitPendingComponent = ...
exporterIdent: 'pendingComponent', // export { SplitPendingComponent as pendingComponent }
},
],
[
'errorComponent',
{
routeIdent: 'errorComponent',
localImporterIdent: '$$splitErrorComponentImporter', // const $$splitErrorComponentImporter = () => import('...')
splitStrategy: 'lazyRouteComponent',
localExporterIdent: 'SplitErrorComponent', // const SplitErrorComponent = ...
exporterIdent: 'errorComponent', // export { SplitErrorComponent as errorComponent }
},
],
[
'notFoundComponent',
{
routeIdent: 'notFoundComponent',
localImporterIdent: '$$splitNotFoundComponentImporter', // const $$splitNotFoundComponentImporter = () => import('...')
splitStrategy: 'lazyRouteComponent',
localExporterIdent: 'SplitNotFoundComponent', // const SplitNotFoundComponent = ...
exporterIdent: 'notFoundComponent', // export { SplitNotFoundComponent as notFoundComponent }
},
],
])
const KNOWN_SPLIT_ROUTE_IDENTS = [...SPLIT_NODES_CONFIG.keys()] as const
function addSplitSearchParamToFilename(
filename: string,
grouping: Array<string>,
) {
const [bareFilename] = filename.split('?')
const params = new URLSearchParams()
params.append(tsrSplit, createIdentifier(grouping))
const result = `${bareFilename}?${params.toString()}`
return result
}
function removeSplitSearchParamFromFilename(filename: string) {
const [bareFilename] = filename.split('?')
return bareFilename!
}
// Escapes a value so it can be safely interpolated into a single-quoted
// string literal, e.g. filenames containing `'` would otherwise produce
// unparsable code (#7754)
function escapeSingleQuotedString(value: string) {
return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
}
export function addSharedSearchParamToFilename(filename: string) {
const [bareFilename] = filename.split('?')
return `${bareFilename}?${tsrShared}=1`
}
const splittableCreateRouteFns = ['createFileRoute']
const unsplittableCreateRouteFns = [
'createRootRoute',
'createRootRouteWithContext',
]
const allCreateRouteFns = [
...splittableCreateRouteFns,
...unsplittableCreateRouteFns,
]
/**
* Computes module-level bindings that are shared between split and non-split
* route properties. These bindings need to be extracted into a shared virtual
* module to avoid double-initialization.
*
* 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).
*/
export function computeSharedBindings(opts: {
code: string
filename?: string
codeSplitGroupings: CodeSplitGroupings
}): Set<string> {
const ast = parseAst(opts)
// 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
// the expensive babel.traverse entirely.
const localModuleLevelBindings = new Set<string>()
for (const node of ast.program.body) {
collectLocalBindingsFromStatement(node, localModuleLevelBindings)
}
// File-based routes always export a route config binding (usually `Route`).
// This must never be extracted into the shared module.
localModuleLevelBindings.delete('Route')
if (localModuleLevelBindings.size === 0) {
return new Set()
}
function findIndexForSplitNode(str: string) {
return opts.codeSplitGroupings.findIndex((group) =>
group.includes(str as any),
)
}
// Find the route options object — needs babel.traverse for scope resolution
let routeOptions: t.ObjectExpression | undefined
babel.traverse(ast, {
CallExpression(path) {
if (!t.isIdentifier(path.node.callee)) return
if (!splittableCreateRouteFns.includes(path.node.callee.name)) return
if (t.isCallExpression(path.parentPath.node)) {
const opts = resolveIdentifier(path, path.parentPath.node.arguments[0])
if (t.isObjectExpression(opts)) routeOptions = opts
} else if (t.isVariableDeclarator(path.parentPath.node)) {
const caller = resolveIdentifier(path, path.parentPath.node.init)
if (t.isCallExpression(caller)) {
const opts = resolveIdentifier(path, caller.arguments[0])
if (t.isObjectExpression(opts)) routeOptions = opts
}
}
},
})
if (!routeOptions) return new Set()
// Fast path: if fewer than 2 distinct groups are referenced by route options,
// nothing can be shared and we can skip the rest of the work.
const splitGroupsPresent = new Set<number>()
let hasNonSplit = false
for (const prop of routeOptions.properties) {
if (!t.isObjectProperty(prop)) continue
const key = getObjectPropertyKeyName(prop)
if (!key) continue
if (key === 'codeSplitGroupings') continue
if (t.isIdentifier(prop.value) && prop.value.name === 'undefined') continue
const groupIndex = findIndexForSplitNode(key) // -1 if non-split
if (groupIndex === -1) {
hasNonSplit = true
} else {
splitGroupsPresent.add(groupIndex)
}
}
if (!hasNonSplit && splitGroupsPresent.size < 2) return new Set()
// Build dependency graph up front — needed for transitive expansion per-property.
// This graph excludes `Route` (deleted above) so group attribution works correctly.
const declMap = buildDeclarationMap(ast)
const depGraph = buildDependencyGraph(declMap, localModuleLevelBindings)
// Build a second dependency graph that includes `Route` so we can detect
// bindings that transitively depend on it. Such bindings must NOT be
// extracted into the shared module because they would drag the Route
// singleton with them, duplicating it across modules.
const allLocalBindings = new Set(localModuleLevelBindings)
allLocalBindings.add('Route')
const fullDepGraph = buildDependencyGraph(declMap, allLocalBindings)
// For each route property, track which "group" it belongs to.
// Non-split properties get group index -1.
// Split properties get their codeSplitGroupings index (0, 1, ...).
// A binding is "shared" if it appears in 2+ distinct groups.
// We expand each property's refs transitively BEFORE comparing groups,
// so indirect refs (e.g., component: MyComp where MyComp uses `shared`)
// are correctly attributed.
const refsByGroup = new Map<string, Set<number>>()
for (const prop of routeOptions.properties) {
if (!t.isObjectProperty(prop)) continue
const key = getObjectPropertyKeyName(prop)
if (!key) continue
if (key === 'codeSplitGroupings') continue
const groupIndex = findIndexForSplitNode(key) // -1 if non-split
const directRefs = collectModuleLevelRefsFromNode(
prop.value,
localModuleLevelBindings,
)
// Expand transitively: if component references SharedComp which references
// `shared`, then `shared` is also attributed to component's group.
const allRefs = new Set(directRefs)
expandTransitively(allRefs, depGraph)
for (const ref of allRefs) {
let groups = refsByGroup.get(ref)
if (!groups) {
groups = new Set()
refsByGroup.set(ref, groups)
}
groups.add(groupIndex)
}
}
// Shared = bindings appearing in 2+ distinct groups
const shared = new Set<string>()
for (const [name, groups] of refsByGroup) {
if (groups.size >= 2) shared.add(name)
}
// Destructured declarators (e.g. `const { a, b } = fn()`) must be treated
// as a single initialization unit. Even if each binding is referenced by
// only one group, if *different* bindings from the same declarator are
// referenced by different groups, the declarator must be extracted to the
// shared module to avoid double initialization.
expandSharedDestructuredDeclarators(ast, refsByGroup, shared)
if (shared.size === 0) return shared
// If any binding from a destructured declaration is shared,
// all bindings from that declaration must be shared
expandDestructuredDeclarations(ast, shared)
// Remove shared bindings that transitively depend on `Route`.
// The Route singleton must stay in the reference file; extracting a
// binding that references it would duplicate Route in the shared module.
removeBindingsTransitivelyDependingOn(shared, fullDepGraph, ['Route'])
return shared
}
/**
* Find which shared bindings are user-exported in the original source.
* These need to be re-exported from the shared module.
*/
function findExportedSharedBindings(
ast: t.File,
sharedBindings: Set<string>,
): Set<string> {
const exported = new Set<string>()
for (const stmt of ast.program.body) {
if (!t.isExportNamedDeclaration(stmt) || !stmt.declaration) continue
if (t.isVariableDeclaration(stmt.declaration)) {
for (const decl of stmt.declaration.declarations) {
for (const name of collectIdentifiersFromPattern(decl.id)) {
if (sharedBindings.has(name)) exported.add(name)
}
}
} else if (
t.isFunctionDeclaration(stmt.declaration) &&
stmt.declaration.id
) {
if (sharedBindings.has(stmt.declaration.id.name))
exported.add(stmt.declaration.id.name)
} else if (t.isClassDeclaration(stmt.declaration) && stmt.declaration.id) {
if (sharedBindings.has(stmt.declaration.id.name))
exported.add(stmt.declaration.id.name)
}
}
return exported
}
/**
* Remove declarations of shared bindings from the AST.
* Handles both plain and exported declarations, including destructured patterns.
* Removes the entire statement if all bindings in it are shared.
*/
function removeSharedDeclarations(ast: t.File, sharedBindings: Set<string>) {
ast.program.body = ast.program.body.filter((stmt) => {
const decl =
t.isExportNamedDeclaration(stmt) && stmt.declaration
? stmt.declaration
: stmt
if (t.isVariableDeclaration(decl)) {
// Filter out declarators where all bound names are shared
decl.declarations = decl.declarations.filter((declarator) => {
const names = collectIdentifiersFromPattern(declarator.id)
return !names.every((n) => sharedBindings.has(n))
})
// If no declarators remain, remove the entire statement
if (decl.declarations.length === 0) return false
} else if (t.isFunctionDeclaration(decl) && decl.id) {
if (sharedBindings.has(decl.id.name)) return false
} else if (t.isClassDeclaration(decl) && decl.id) {
if (sharedBindings.has(decl.id.name)) return false
}
return true
})
}
export function compileCodeSplitReferenceRoute(
opts: ParseAstOptions &
CompileCodeSplitReferenceRouteOptions & {
compilerPlugins?: Array<ReferenceRouteCompilerPlugin>
},
): GeneratorResult | null {
const ast = parseAst(opts)
const refIdents = findReferencedIdentifiers(ast)
const knownExportedIdents = new Set<string>()
function findIndexForSplitNode(str: string) {
return opts.codeSplitGroupings.findIndex((group) =>
group.includes(str as any),
)
}
const frameworkOptions = getFrameworkOptions(opts.targetFramework)
const PACKAGE = frameworkOptions.package
const LAZY_ROUTE_COMPONENT_IDENT = frameworkOptions.idents.lazyRouteComponent
const LAZY_FN_IDENT = frameworkOptions.idents.lazyFn
const stableRouteOptionKeys = [
...new Set(
(opts.compilerPlugins ?? []).flatMap(
(plugin) => plugin.getStableRouteOptionKeys?.() ?? [],
),
),
]
let createRouteFn: string
let modified = false as boolean
let hmrAdded = false as boolean
let sharedExportedNames: Set<string> | undefined
babel.traverse(ast, {
Program: {
enter(programPath) {
/**
* If the component for the route is being imported from
* another file, this is to track the path to that file
* the path itself doesn't matter, we just need to keep
* track of it so that we can remove it from the imports
* list if it's not being used like:
*
* `import '../shared/imported'`
*/
const removableImportPaths = new Set<string>([])
programPath.traverse({
CallExpression: (path) => {
if (!t.isIdentifier(path.node.callee)) {
return
}
if (!allCreateRouteFns.includes(path.node.callee.name)) {
return
}
createRouteFn = path.node.callee.name
function babelHandleReference(routeOptions: t.Node | undefined) {
const hasImportedOrDefinedIdentifier = (name: string) => {
return programPath.scope.hasBinding(name)
}
const addRouteHmr = (
insertionPath: babel.NodePath,
routeOptions: t.ObjectExpression,
) => {
if (!opts.addHmr || hmrAdded) {
return
}
opts.compilerPlugins?.forEach((plugin) => {
const pluginResult = plugin.onAddHmr?.({
programPath,
callExpressionPath: path,
insertionPath,
routeOptions,
createRouteFn,
opts: opts as CompileCodeSplitReferenceRouteOptions,
})
if (pluginResult?.modified) {
modified = true
}
})
programPath.pushContainer(
'body',
createRouteHmrStatement(stableRouteOptionKeys, {
hmrStyle: opts.hmrStyle ?? 'vite',
targetFramework: opts.targetFramework,
routeId: opts.hmrRouteId,
}),
)
modified = true
hmrAdded = true
}
if (t.isObjectExpression(routeOptions)) {
const insertionPath = path.getStatementParent() ?? path
opts.compilerPlugins?.forEach((plugin) => {
const pluginResult = plugin.onRouteOptions?.({
programPath,
callExpressionPath: path,
insertionPath,
routeOptions,
createRouteFn,
opts: opts as CompileCodeSplitReferenceRouteOptions,
})
if (pluginResult?.modified) {
modified = true
}
})
if (opts.deleteNodes && opts.deleteNodes.size > 0) {
routeOptions.properties = routeOptions.properties.filter(
(prop) => {
if (t.isObjectProperty(prop)) {
const key = getObjectPropertyKeyName(prop)
if (key && opts.deleteNodes!.has(key as any)) {
modified = true
return false
}
}
return true
},
)
}
if (!splittableCreateRouteFns.includes(createRouteFn)) {
opts.compilerPlugins?.forEach((plugin) => {
const pluginResult = plugin.onUnsplittableRoute?.({
programPath,
callExpressionPath: path,
insertionPath,
routeOptions,
createRouteFn,
opts: opts as CompileCodeSplitReferenceRouteOptions,
})
if (pluginResult?.modified) {
modified = true
}
})
// we can't split this route but we still add HMR handling if enabled
addRouteHmr(insertionPath, routeOptions)
// exit traversal so this route is not split
return programPath.stop()
}
routeOptions.properties.forEach((prop) => {
if (t.isObjectProperty(prop)) {
const key = getObjectPropertyKeyName(prop)
if (key) {
// If the user has not specified a split grouping for this key
// then we should not split it
const codeSplitGroupingByKey = findIndexForSplitNode(key)
if (codeSplitGroupingByKey === -1) {
return
}
const codeSplitGroup = [
...new Set(
opts.codeSplitGroupings[codeSplitGroupingByKey],
),
]
// find key in nodeSplitConfig
const isNodeConfigAvailable = SPLIT_NODES_CONFIG.has(
key as any,
)
if (!isNodeConfigAvailable) {
return
}
// Exit early if the value is a boolean, null, or undefined.
// These values mean "don't use this component, fallback to parent"
// No code splitting needed to preserve fallback behavior
if (
t.isBooleanLiteral(prop.value) ||
t.isNullLiteral(prop.value) ||
(t.isIdentifier(prop.value) &&
prop.value.name === 'undefined')
) {
return
}
const splitNodeMeta = SPLIT_NODES_CONFIG.get(key as any)!
// We need to extract the existing search params from the filename, if any
// and add the relevant codesplitPrefix to them, then write them back to the filename
const splitUrl = addSplitSearchParamToFilename(
opts.filename,
codeSplitGroup,
)
if (
splitNodeMeta.splitStrategy === 'lazyRouteComponent'
) {
const value = prop.value
let shouldSplit = true
if (t.isIdentifier(value)) {
const existingImportPath =
getImportSpecifierAndPathFromLocalName(
programPath,
value.name,
).path
if (existingImportPath) {
removableImportPaths.add(existingImportPath)
}
// exported identifiers should not be split
// since they are already being imported
// and need to be retained in the compiled file
const isExported = hasExport(ast, value)
if (isExported) {
knownExportedIdents.add(value.name)
}
shouldSplit = !isExported
if (shouldSplit) {
removeIdentifierLiteral(path, value)
}
}
if (!shouldSplit) {
return
}
modified = true
// Prepend the import statement to the program along with the importer function
// Check to see if lazyRouteComponent is already imported before attempting
// to import it again
if (
!hasImportedOrDefinedIdentifier(
LAZY_ROUTE_COMPONENT_IDENT,
)
) {
programPath.unshiftContainer('body', [
template.statement(
`import { ${LAZY_ROUTE_COMPONENT_IDENT} } from '${PACKAGE}'`,
)(),
])
}
// Check to see if the importer function is already defined
// If not, define it with the dynamic import statement
if (
!hasImportedOrDefinedIdentifier(
splitNodeMeta.localImporterIdent,
)
) {
programPath.unshiftContainer('body', [
template.statement(
`const ${splitNodeMeta.localImporterIdent} = () => import('${escapeSingleQuotedString(splitUrl)}')`,
)(),
])
}
const insertionPath = path.getStatementParent() ?? path
let splitPropValue: t.Expression | undefined
for (const plugin of opts.compilerPlugins ?? []) {
const pluginPropValue = plugin.onSplitRouteProperty?.(
{
programPath,
callExpressionPath: path,
insertionPath,
routeOptions,
prop,
splitNodeMeta,
lazyRouteComponentIdent:
LAZY_ROUTE_COMPONENT_IDENT,
opts,
},
)
if (!pluginPropValue) {
continue
}
modified = true
splitPropValue = pluginPropValue
break
}
if (splitPropValue) {
prop.value = splitPropValue
} else {
prop.value = template.expression(
`${LAZY_ROUTE_COMPONENT_IDENT}(${splitNodeMeta.localImporterIdent}, '${splitNodeMeta.exporterIdent}')`,
)()
}
// add HMR handling
addRouteHmr(insertionPath, routeOptions)
} else {
// if (splitNodeMeta.splitStrategy === 'lazyFn') {
const value = prop.value
let shouldSplit = true
if (t.isIdentifier(value)) {
const existingImportPath =
getImportSpecifierAndPathFromLocalName(
programPath,
value.name,
).path
if (existingImportPath) {
removableImportPaths.add(existingImportPath)
}
// exported identifiers should not be split
// since they are already being imported
// and need to be retained in the compiled file
const isExported = hasExport(ast, value)
if (isExported) {
knownExportedIdents.add(value.name)
}
shouldSplit = !isExported
if (shouldSplit) {
removeIdentifierLiteral(path, value)
}
}
if (!shouldSplit) {
return
}
modified = true
// Prepend the import statement to the program along with the importer function
if (!hasImportedOrDefinedIdentifier(LAZY_FN_IDENT)) {
programPath.unshiftContainer(
'body',
template.smart(
`import { ${LAZY_FN_IDENT} } from '${PACKAGE}'`,
)(),
)
}
// Check to see if the importer function is already defined
// If not, define it with the dynamic import statement
if (
!hasImportedOrDefinedIdentifier(
splitNodeMeta.localImporterIdent,
)
) {
programPath.unshiftContainer('body', [
template.statement(
`const ${splitNodeMeta.localImporterIdent} = () => import('${escapeSingleQuotedString(splitUrl)}')`,
)(),
])
}
// Add the lazyFn call with the dynamic import to the prop value
prop.value = template.expression(
`${LAZY_FN_IDENT}(${splitNodeMeta.localImporterIdent}, '${splitNodeMeta.exporterIdent}')`,
)()
}
}
}
programPath.scope.crawl()
})
addRouteHmr(insertionPath, routeOptions)
}
}
if (t.isCallExpression(path.parentPath.node)) {
// createFileRoute('/')({ ... })
const options = resolveIdentifier(
path,
path.parentPath.node.arguments[0],
)
babelHandleReference(options)
} else if (t.isVariableDeclarator(path.parentPath.node)) {
// createFileRoute({ ... })
const caller = resolveIdentifier(path, path.parentPath.node.init)
if (t.isCallExpression(caller)) {
const options = resolveIdentifier(path, caller.arguments[0])
babelHandleReference(options)
}
}
},
})
/**
* If the component for the route is being imported,
* and it's not being used, remove the import statement
* from the program, by checking that the import has no
* specifiers
*/
if (removableImportPaths.size > 0) {
modified = true
programPath.traverse({
ImportDeclaration(path) {
if (path.node.specifiers.length > 0) return
if (removableImportPaths.has(path.node.source.value)) {
path.remove()
}
},
})
}
// Handle shared bindings inside the Program visitor so we have
// access to programPath for cheap refIdents registration.
if (opts.sharedBindings && opts.sharedBindings.size > 0) {
sharedExportedNames = findExportedSharedBindings(
ast,
opts.sharedBindings,
)
removeSharedDeclarations(ast, opts.sharedBindings)
const sharedModuleUrl = addSharedSearchParamToFilename(opts.filename)
const sharedImportSpecifiers = [...opts.sharedBindings].map((name) =>
t.importSpecifier(t.identifier(name), t.identifier(name)),
)
const [sharedImportPath] = programPath.unshiftContainer(
'body',
t.importDeclaration(
sharedImportSpecifiers,
t.stringLiteral(sharedModuleUrl),
),
)
// Register import specifier locals in refIdents so DCE can remove unused ones
sharedImportPath.traverse({
Identifier(identPath) {
if (
identPath.parentPath.isImportSpecifier() &&
identPath.key === 'local'
) {
refIdents.add(identPath)
}
},
})
// Re-export user-exported shared bindings from the shared module
if (sharedExportedNames.size > 0) {
const reExportSpecifiers = [...sharedExportedNames].map((name) =>
t.exportSpecifier(t.identifier(name), t.identifier(name)),
)
programPath.pushContainer(
'body',
t.exportNamedDeclaration(
null,
reExportSpecifiers,
t.stringLiteral(sharedModuleUrl),
),
)
}
}
},
},
})
if (!modified) {
return null
}
deadCodeElimination(ast, refIdents)
// if there are exported identifiers, then we need to add a warning
// to the file to let the user know that the exported identifiers
// will not in the split file but in the original file, therefore
// increasing the bundle size
if (knownExportedIdents.size > 0) {
const warningMessage = createNotExportableMessage(
opts.filename,
knownExportedIdents,
)
console.warn(warningMessage)
// append this warning to the file using a template
if (process.env.NODE_ENV !== 'production') {
const warningTemplate = template.statement(
`console.warn(${JSON.stringify(warningMessage)})`,
)()
ast.program.body.unshift(warningTemplate)
}
}
const result = generateFromAst(ast, {
sourceMaps: true,
sourceFileName: opts.filename,
filename: opts.filename,
})
// @babel/generator does not populate sourcesContent because it only has
// the AST, not the original text. Without this, Vite's composed
// sourcemap omits the original source, causing downstream consumers
// (e.g. import-protection snippet display) to fall back to the shorter
// compiled output and fail to resolve original line numbers.
if (result.map) {
result.map.sourcesContent = [opts.code]
}
return result
}
export function compileCodeSplitVirtualRoute(
opts: ParseAstOptions & {
splitTargets: Array<SplitRouteIdentNodes>
filename: string
sharedBindings?: Set<string>
},
): GeneratorResult {
const ast = parseAst(opts)
const refIdents = findReferencedIdentifiers(ast)
// Remove shared declarations BEFORE babel.traverse so the scope never sees
// conflicting bindings (avoids checkBlockScopedCollisions crash in DCE)
if (opts.sharedBindings && opts.sharedBindings.size > 0) {
removeSharedDeclarations(ast, opts.sharedBindings)
}
const intendedSplitNodes = new Set(opts.splitTargets)
const knownExportedIdents = new Set<string>()
babel.traverse(ast, {
Program: {
enter(programPath) {
const trackedNodesToSplitByType: Record<
SplitRouteIdentNodes,
{ node: t.Node | undefined; meta: SplitNodeMeta } | undefined
> = {
component: undefined,
loader: undefined,
pendingComponent: undefined,
errorComponent: undefined,
notFoundComponent: undefined,
}
// Find and track all the known split-able nodes
programPath.traverse({
CallExpression: (path) => {
if (!t.isIdentifier(path.node.callee)) {
return
}
if (!splittableCreateRouteFns.includes(path.node.callee.name)) {
return
}
function babelHandleVirtual(options: t.Node | undefined) {
if (t.isObjectExpression(options)) {
options.properties.forEach((prop) => {
if (t.isObjectProperty(prop)) {
// do not use `intendedSplitNodes` here
// since we have special considerations that need
// to be accounted for like (not splitting exported identifiers)
KNOWN_SPLIT_ROUTE_IDENTS.forEach((splitType) => {
if (getObjectPropertyKeyName(prop) !== splitType) {
return
}
const value = prop.value
// If the value for the `key` is `undefined`, then we don't need to include it
// in the split file, so we can just return, since it will kept in-place in the
// reference file
// This is useful for cases like: `createFileRoute('/')({ component: undefined })`
if (t.isIdentifier(value) && value.name === 'undefined') {
return
}
let isExported = false
if (t.isIdentifier(value)) {
isExported = hasExport(ast, value)
if (isExported) {
knownExportedIdents.add(value.name)
}
}
// If the node is exported, we need to remove
// the export from the split file
if (isExported && t.isIdentifier(value)) {
removeExports(ast, value)
} else {
const meta = SPLIT_NODES_CONFIG.get(splitType)!
trackedNodesToSplitByType[splitType] = {
node: prop.value,
meta,
}
}
})
}
})
// Remove all of the options
options.properties = []
}
}
if (t.isCallExpression(path.parentPath.node)) {
// createFileRoute('/')({ ... })
const options = resolveIdentifier(
path,
path.parentPath.node.arguments[0],
)
babelHandleVirtual(options)
} else if (t.isVariableDeclarator(path.parentPath.node)) {
// createFileRoute({ ... })
const caller = resolveIdentifier(path, path.parentPath.node.init)
if (t.isCallExpression(caller)) {
const options = resolveIdentifier(path, caller.arguments[0])
babelHandleVirtual(options)
}
}
},
})
// Start the transformation to only exported the intended split nodes
intendedSplitNodes.forEach((SPLIT_TYPE) => {