-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathplugin.ts
2142 lines (1930 loc) · 69.6 KB
/
plugin.ts
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
// We can only import types from Vite at the top level since we're in a CJS
// context but want to use Vite's ESM build to avoid deprecation warnings
import type * as Vite from "vite";
import { type BinaryLike, createHash } from "node:crypto";
import * as path from "node:path";
import * as url from "node:url";
import * as fse from "fs-extra";
import * as babel from "@babel/core";
import {
unstable_setDevServerHooks as setDevServerHooks,
createRequestHandler,
matchRoutes,
} from "react-router";
import type {
RequestHandler,
ServerBuild,
DataRouteObject,
} from "react-router";
import {
init as initEsModuleLexer,
parse as esModuleLexer,
} from "es-module-lexer";
import jsesc from "jsesc";
import colors from "picocolors";
import * as Typegen from "../typegen";
import { type RouteManifestEntry, type RouteManifest } from "../config/routes";
import type { Manifest as ReactRouterManifest } from "../manifest";
import invariant from "../invariant";
import { generate, parse } from "./babel";
import type { NodeRequestHandler } from "./node-adapter";
import { fromNodeRequest, toNodeRequest } from "./node-adapter";
import { getStylesForUrl, isCssModulesFile } from "./styles";
import * as VirtualModule from "./virtual-module";
import { resolveFileUrl } from "./resolve-file-url";
import { combineURLs } from "./combine-urls";
import { removeExports } from "./remove-exports";
import { preloadVite, getVite } from "./vite";
import {
type ResolvedReactRouterConfig,
type ConfigLoader,
createConfigLoader,
resolveEntryFiles,
ssrExternals,
} from "../config/config";
import * as WithProps from "./with-props";
export async function resolveViteConfig({
configFile,
mode,
root,
}: {
configFile?: string;
mode?: string;
root: string;
}) {
let vite = getVite();
let viteConfig = await vite.resolveConfig(
{ mode, configFile, root },
"build", // command
"production", // default mode
"production" // default NODE_ENV
);
if (typeof viteConfig.build.manifest === "string") {
throw new Error("Custom Vite manifest paths are not supported");
}
return viteConfig;
}
export async function extractPluginContext(viteConfig: Vite.ResolvedConfig) {
return viteConfig["__reactRouterPluginContext" as keyof typeof viteConfig] as
| ReactRouterPluginContext
| undefined;
}
const SERVER_ONLY_ROUTE_EXPORTS = ["loader", "action", "headers"];
const CLIENT_ROUTE_EXPORTS = [
"clientAction",
"clientLoader",
"default",
"ErrorBoundary",
"handle",
"HydrateFallback",
"Layout",
"links",
"meta",
"shouldRevalidate",
];
/** This is used to manage a build optimization to remove unused route exports
from the client build output. This is important in cases where custom route
exports are only ever used on the server. Without this optimization we can't
tree-shake any unused custom exports because routes are entry points. */
const BUILD_CLIENT_ROUTE_QUERY_STRING = "?__react-router-build-client-route";
export type ServerBundleBuildConfig = {
routes: RouteManifest;
serverBundleId: string;
};
type ReactRouterPluginSsrBuildContext =
| {
isSsrBuild: false;
getReactRouterServerManifest?: never;
serverBundleBuildConfig?: never;
}
| {
isSsrBuild: true;
getReactRouterServerManifest: () => Promise<ReactRouterManifest>;
serverBundleBuildConfig: ServerBundleBuildConfig | null;
};
export type ReactRouterPluginContext = ReactRouterPluginSsrBuildContext & {
rootDirectory: string;
entryClientFilePath: string;
entryServerFilePath: string;
publicPath: string;
reactRouterConfig: ResolvedReactRouterConfig;
viteManifestEnabled: boolean;
};
let virtualHmrRuntime = VirtualModule.create("hmr-runtime");
let virtualInjectHmrRuntime = VirtualModule.create("inject-hmr-runtime");
const resolveRelativeRouteFilePath = (
route: RouteManifestEntry,
reactRouterConfig: ResolvedReactRouterConfig
) => {
let vite = getVite();
let file = route.file;
let fullPath = path.resolve(reactRouterConfig.appDirectory, file);
return vite.normalizePath(fullPath);
};
let virtual = {
serverBuild: VirtualModule.create("server-build"),
serverManifest: VirtualModule.create("server-manifest"),
browserManifest: VirtualModule.create("browser-manifest"),
};
let invalidateVirtualModules = (viteDevServer: Vite.ViteDevServer) => {
Object.values(virtual).forEach((vmod) => {
let mod = viteDevServer.moduleGraph.getModuleById(vmod.resolvedId);
if (mod) {
viteDevServer.moduleGraph.invalidateModule(mod);
}
});
};
const getHash = (source: BinaryLike, maxLength?: number): string => {
let hash = createHash("sha256").update(source).digest("hex");
return typeof maxLength === "number" ? hash.slice(0, maxLength) : hash;
};
const resolveChunk = (
ctx: ReactRouterPluginContext,
viteManifest: Vite.Manifest,
absoluteFilePath: string
) => {
let vite = getVite();
let rootRelativeFilePath = vite.normalizePath(
path.relative(ctx.rootDirectory, absoluteFilePath)
);
let entryChunk =
viteManifest[rootRelativeFilePath + BUILD_CLIENT_ROUTE_QUERY_STRING] ??
viteManifest[rootRelativeFilePath];
if (!entryChunk) {
let knownManifestKeys = Object.keys(viteManifest)
.map((key) => '"' + key + '"')
.join(", ");
throw new Error(
`No manifest entry found for "${rootRelativeFilePath}". Known manifest keys: ${knownManifestKeys}`
);
}
return entryChunk;
};
const getReactRouterManifestBuildAssets = (
ctx: ReactRouterPluginContext,
viteManifest: Vite.Manifest,
entryFilePath: string,
prependedAssetFilePaths: string[] = []
): ReactRouterManifest["entry"] & { css: string[] } => {
let entryChunk = resolveChunk(ctx, viteManifest, entryFilePath);
// This is here to support prepending client entry assets to the root route
let prependedAssetChunks = prependedAssetFilePaths.map((filePath) =>
resolveChunk(ctx, viteManifest, filePath)
);
let chunks = resolveDependantChunks(viteManifest, [
...prependedAssetChunks,
entryChunk,
]);
return {
module: `${ctx.publicPath}${entryChunk.file}`,
imports:
dedupe(chunks.flatMap((e) => e.imports ?? [])).map((imported) => {
return `${ctx.publicPath}${viteManifest[imported].file}`;
}) ?? [],
css:
dedupe(chunks.flatMap((e) => e.css ?? [])).map((href) => {
return `${ctx.publicPath}${href}`;
}) ?? [],
};
};
function resolveDependantChunks(
viteManifest: Vite.Manifest,
entryChunks: Vite.ManifestChunk[]
): Vite.ManifestChunk[] {
let chunks = new Set<Vite.ManifestChunk>();
function walk(chunk: Vite.ManifestChunk) {
if (chunks.has(chunk)) {
return;
}
chunks.add(chunk);
if (chunk.imports) {
for (let importKey of chunk.imports) {
walk(viteManifest[importKey]);
}
}
}
for (let entryChunk of entryChunks) {
walk(entryChunk);
}
return Array.from(chunks);
}
function dedupe<T>(array: T[]): T[] {
return [...new Set(array)];
}
const writeFileSafe = async (file: string, contents: string): Promise<void> => {
await fse.ensureDir(path.dirname(file));
await fse.writeFile(file, contents);
};
const getRouteManifestModuleExports = async (
viteChildCompiler: Vite.ViteDevServer | null,
ctx: ReactRouterPluginContext
): Promise<Record<string, string[]>> => {
let entries = await Promise.all(
Object.entries(ctx.reactRouterConfig.routes).map(async ([key, route]) => {
let sourceExports = await getRouteModuleExports(
viteChildCompiler,
ctx,
route.file
);
return [key, sourceExports] as const;
})
);
return Object.fromEntries(entries);
};
const getRouteModuleExports = async (
viteChildCompiler: Vite.ViteDevServer | null,
ctx: ReactRouterPluginContext,
routeFile: string,
readRouteFile?: () => string | Promise<string>
): Promise<string[]> => {
if (!viteChildCompiler) {
throw new Error("Vite child compiler not found");
}
// We transform the route module code with the Vite child compiler so that we
// can parse the exports from non-JS files like MDX. This ensures that we can
// understand the exports from anything that Vite can compile to JS, not just
// the route file formats that the Remix compiler historically supported.
let ssr = true;
let { pluginContainer, moduleGraph } = viteChildCompiler;
let routePath = path.resolve(ctx.reactRouterConfig.appDirectory, routeFile);
let url = resolveFileUrl(ctx, routePath);
let resolveId = async () => {
let result = await pluginContainer.resolveId(url, undefined, { ssr });
if (!result) throw new Error(`Could not resolve module ID for ${url}`);
return result.id;
};
let [id, code] = await Promise.all([
resolveId(),
readRouteFile?.() ?? fse.readFile(routePath, "utf-8"),
// pluginContainer.transform(...) fails if we don't do this first:
moduleGraph.ensureEntryFromUrl(url, ssr),
]);
let transformed = await pluginContainer.transform(code, id, { ssr });
let [, exports] = esModuleLexer(transformed.code);
let exportNames = exports.map((e) => e.n);
return exportNames;
};
const getServerBundleBuildConfig = (
viteUserConfig: Vite.UserConfig
): ServerBundleBuildConfig | null => {
if (
!("__reactRouterServerBundleBuildConfig" in viteUserConfig) ||
!viteUserConfig.__reactRouterServerBundleBuildConfig
) {
return null;
}
return viteUserConfig.__reactRouterServerBundleBuildConfig as ServerBundleBuildConfig;
};
export let getServerBuildDirectory = (ctx: ReactRouterPluginContext) =>
path.join(
ctx.reactRouterConfig.buildDirectory,
"server",
...(ctx.serverBundleBuildConfig
? [ctx.serverBundleBuildConfig.serverBundleId]
: [])
);
let getClientBuildDirectory = (reactRouterConfig: ResolvedReactRouterConfig) =>
path.join(reactRouterConfig.buildDirectory, "client");
let defaultEntriesDir = path.resolve(
path.dirname(require.resolve("@react-router/dev/package.json")),
"dist",
"config",
"defaults"
);
let defaultEntries = fse
.readdirSync(defaultEntriesDir)
.map((filename) => path.join(defaultEntriesDir, filename));
invariant(defaultEntries.length > 0, "No default entries found");
type MaybePromise<T> = T | Promise<T>;
let reactRouterDevLoadContext: (
request: Request
) => MaybePromise<Record<string, unknown>> = () => ({});
export let setReactRouterDevLoadContext = (
loadContext: (request: Request) => MaybePromise<Record<string, unknown>>
) => {
reactRouterDevLoadContext = loadContext;
};
type ReactRouterVitePlugin = () => Vite.Plugin[];
/**
* React Router [Vite plugin.](https://vitejs.dev/guide/using-plugins.html)
*/
export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
let rootDirectory: string;
let viteCommand: Vite.ResolvedConfig["command"];
let viteUserConfig: Vite.UserConfig;
let viteConfigEnv: Vite.ConfigEnv;
let viteConfig: Vite.ResolvedConfig | undefined;
let cssModulesManifest: Record<string, string> = {};
let viteChildCompiler: Vite.ViteDevServer | null = null;
let reactRouterConfigLoader: ConfigLoader;
let typegenWatcherPromise: Promise<Typegen.Watcher> | undefined;
let logger: Vite.Logger;
let firstLoad = true;
// This is initialized by `updatePluginContext` during Vite's `config`
// hook, so most of the code can assume this defined without null check.
// During dev, `updatePluginContext` is called again on every config file
// change or route file addition/removal.
let ctx: ReactRouterPluginContext;
/** Mutates `ctx` as a side-effect */
let updatePluginContext = async (): Promise<void> => {
let reactRouterConfig: ResolvedReactRouterConfig;
let reactRouterConfigResult = await reactRouterConfigLoader.getConfig();
if (reactRouterConfigResult.ok) {
reactRouterConfig = reactRouterConfigResult.value;
} else {
logger.error(reactRouterConfigResult.error);
if (firstLoad) {
process.exit(1);
}
return;
}
let { entryClientFilePath, entryServerFilePath } = await resolveEntryFiles({
rootDirectory,
reactRouterConfig,
});
let publicPath = viteUserConfig.base ?? "/";
if (
reactRouterConfig.basename !== "/" &&
viteCommand === "serve" &&
!viteUserConfig.server?.middlewareMode &&
!reactRouterConfig.basename.startsWith(publicPath)
) {
logger.error(
colors.red(
"When using the React Router `basename` and the Vite `base` config, " +
"the `basename` config must begin with `base` for the default " +
"Vite dev server."
)
);
process.exit(1);
}
let viteManifestEnabled = viteUserConfig.build?.manifest === true;
let ssrBuildCtx: ReactRouterPluginSsrBuildContext =
viteConfigEnv.isSsrBuild && viteCommand === "build"
? {
isSsrBuild: true,
getReactRouterServerManifest: async () =>
(await generateReactRouterManifestsForBuild())
.reactRouterServerManifest,
serverBundleBuildConfig: getServerBundleBuildConfig(viteUserConfig),
}
: { isSsrBuild: false };
firstLoad = false;
ctx = {
reactRouterConfig,
rootDirectory,
entryClientFilePath,
entryServerFilePath,
publicPath,
viteManifestEnabled,
...ssrBuildCtx,
};
};
let pluginIndex = (pluginName: string) => {
invariant(viteConfig);
return viteConfig.plugins.findIndex((plugin) => plugin.name === pluginName);
};
let getServerEntry = async () => {
invariant(viteConfig, "viteconfig required to generate the server entry");
let routes = ctx.serverBundleBuildConfig
? // For server bundle builds, the server build should only import the
// routes for this bundle rather than importing all routes
ctx.serverBundleBuildConfig.routes
: // Otherwise, all routes are imported as usual
ctx.reactRouterConfig.routes;
return `
import * as entryServer from ${JSON.stringify(
resolveFileUrl(ctx, ctx.entryServerFilePath)
)};
${Object.keys(routes)
.map((key, index) => {
let route = routes[key]!;
return `import * as route${index} from ${JSON.stringify(
resolveFileUrl(
ctx,
resolveRelativeRouteFilePath(route, ctx.reactRouterConfig)
)
)};`;
})
.join("\n")}
export { default as assets } from ${JSON.stringify(
virtual.serverManifest.id
)};
export const assetsBuildDirectory = ${JSON.stringify(
path.relative(
ctx.rootDirectory,
getClientBuildDirectory(ctx.reactRouterConfig)
)
)};
export const basename = ${JSON.stringify(ctx.reactRouterConfig.basename)};
export const future = ${JSON.stringify(ctx.reactRouterConfig.future)};
export const isSpaMode = ${
!ctx.reactRouterConfig.ssr && ctx.reactRouterConfig.prerender == null
};
export const publicPath = ${JSON.stringify(ctx.publicPath)};
export const entry = { module: entryServer };
export const routes = {
${Object.keys(routes)
.map((key, index) => {
let route = routes[key]!;
return `${JSON.stringify(key)}: {
id: ${JSON.stringify(route.id)},
parentId: ${JSON.stringify(route.parentId)},
path: ${JSON.stringify(route.path)},
index: ${JSON.stringify(route.index)},
caseSensitive: ${JSON.stringify(route.caseSensitive)},
module: route${index}
}`;
})
.join(",\n ")}
};`;
};
let loadViteManifest = async (directory: string) => {
let manifestContents = await fse.readFile(
path.resolve(directory, ".vite", "manifest.json"),
"utf-8"
);
return JSON.parse(manifestContents) as Vite.Manifest;
};
let hasDependency = (name: string) => {
try {
return Boolean(require.resolve(name, { paths: [ctx.rootDirectory] }));
} catch (err) {
return false;
}
};
let getViteManifestAssetPaths = (
viteManifest: Vite.Manifest
): Set<string> => {
// Get .css?url imports and CSS entry points
let cssUrlPaths = Object.values(viteManifest)
.filter((chunk) => chunk.file.endsWith(".css"))
.map((chunk) => chunk.file);
// Get bundled CSS files and generic asset types
let chunkAssetPaths = Object.values(viteManifest).flatMap(
(chunk) => chunk.assets ?? []
);
return new Set([...cssUrlPaths, ...chunkAssetPaths]);
};
let generateReactRouterManifestsForBuild = async (): Promise<{
reactRouterBrowserManifest: ReactRouterManifest;
reactRouterServerManifest: ReactRouterManifest;
}> => {
invariant(viteConfig);
let viteManifest = await loadViteManifest(
getClientBuildDirectory(ctx.reactRouterConfig)
);
let entry = getReactRouterManifestBuildAssets(
ctx,
viteManifest,
ctx.entryClientFilePath
);
let browserRoutes: ReactRouterManifest["routes"] = {};
let serverRoutes: ReactRouterManifest["routes"] = {};
let routeManifestExports = await getRouteManifestModuleExports(
viteChildCompiler,
ctx
);
for (let [key, route] of Object.entries(ctx.reactRouterConfig.routes)) {
let routeFilePath = path.join(
ctx.reactRouterConfig.appDirectory,
route.file
);
let sourceExports = routeManifestExports[key];
let isRootRoute = route.parentId === undefined;
let routeManifestEntry = {
id: route.id,
parentId: route.parentId,
path: route.path,
index: route.index,
caseSensitive: route.caseSensitive,
hasAction: sourceExports.includes("action"),
hasLoader: sourceExports.includes("loader"),
hasClientAction: sourceExports.includes("clientAction"),
hasClientLoader: sourceExports.includes("clientLoader"),
hasErrorBoundary: sourceExports.includes("ErrorBoundary"),
...getReactRouterManifestBuildAssets(
ctx,
viteManifest,
routeFilePath,
// If this is the root route, we also need to include assets from the
// client entry file as this is a common way for consumers to import
// global reset styles, etc.
isRootRoute ? [ctx.entryClientFilePath] : []
),
};
browserRoutes[key] = routeManifestEntry;
let serverBundleRoutes = ctx.serverBundleBuildConfig?.routes;
if (!serverBundleRoutes || serverBundleRoutes[key]) {
serverRoutes[key] = routeManifestEntry;
}
}
let fingerprintedValues = { entry, routes: browserRoutes };
let version = getHash(JSON.stringify(fingerprintedValues), 8);
let manifestPath = path.posix.join(
viteConfig.build.assetsDir,
`manifest-${version}.js`
);
let url = `${ctx.publicPath}${manifestPath}`;
let nonFingerprintedValues = { url, version };
let reactRouterBrowserManifest: ReactRouterManifest = {
...fingerprintedValues,
...nonFingerprintedValues,
};
// Write the browser manifest to disk as part of the build process
await writeFileSafe(
path.join(getClientBuildDirectory(ctx.reactRouterConfig), manifestPath),
`window.__reactRouterManifest=${JSON.stringify(
reactRouterBrowserManifest
)};`
);
// The server manifest is the same as the browser manifest, except for
// server bundle builds which only includes routes for the current bundle,
// otherwise the server and client have the same routes
let reactRouterServerManifest: ReactRouterManifest = {
...reactRouterBrowserManifest,
routes: serverRoutes,
};
return {
reactRouterBrowserManifest,
reactRouterServerManifest,
};
};
// In dev, the server and browser manifests are the same
let getReactRouterManifestForDev = async (): Promise<ReactRouterManifest> => {
let routes: ReactRouterManifest["routes"] = {};
let routeManifestExports = await getRouteManifestModuleExports(
viteChildCompiler,
ctx
);
for (let [key, route] of Object.entries(ctx.reactRouterConfig.routes)) {
let sourceExports = routeManifestExports[key];
routes[key] = {
id: route.id,
parentId: route.parentId,
path: route.path,
index: route.index,
caseSensitive: route.caseSensitive,
module: combineURLs(
ctx.publicPath,
resolveFileUrl(
ctx,
resolveRelativeRouteFilePath(route, ctx.reactRouterConfig)
)
),
hasAction: sourceExports.includes("action"),
hasLoader: sourceExports.includes("loader"),
hasClientAction: sourceExports.includes("clientAction"),
hasClientLoader: sourceExports.includes("clientLoader"),
hasErrorBoundary: sourceExports.includes("ErrorBoundary"),
imports: [],
};
}
return {
version: String(Math.random()),
url: combineURLs(ctx.publicPath, virtual.browserManifest.url),
hmr: {
runtime: combineURLs(ctx.publicPath, virtualInjectHmrRuntime.url),
},
entry: {
module: combineURLs(
ctx.publicPath,
resolveFileUrl(ctx, ctx.entryClientFilePath)
),
imports: [],
},
routes,
};
};
return [
{
name: "react-router",
config: async (_viteUserConfig, _viteConfigEnv) => {
// Preload Vite's ESM build up-front as soon as we're in an async context
await preloadVite();
// Ensure sync import of Vite works after async preload
let vite = getVite();
viteUserConfig = _viteUserConfig;
viteConfigEnv = _viteConfigEnv;
viteCommand = viteConfigEnv.command;
// This is a compatibility layer for Vite 5. Default conditions were
// automatically added to any custom conditions in Vite 5, but Vite 6
// removed this behavior. Instead, the default conditions are overridden
// by any custom conditions. If we wish to retain the default
// conditions, we need to manually merge them using the provided default
// conditions arrays exported from Vite. In Vite 5, these default
// conditions arrays do not exist.
// https://vite.dev/guide/migration.html#default-value-for-resolve-conditions
let viteClientConditions: string[] = [
...(vite.defaultClientConditions ?? []),
];
let packageRoot = path.dirname(
require.resolve("@react-router/dev/package.json")
);
let { moduleSyncEnabled } = await import(
`file:///${path.join(packageRoot, "module-sync-enabled/index.mjs")}`
);
let viteServerConditions: string[] = [
...(vite.defaultServerConditions ?? []),
...(moduleSyncEnabled ? ["module-sync"] : []),
];
logger = vite.createLogger(viteUserConfig.logLevel, {
prefix: "[react-router]",
});
rootDirectory =
viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
if (viteCommand === "serve") {
typegenWatcherPromise = Typegen.watch(rootDirectory, {
// ignore `info` logs from typegen since they are redundant when Vite plugin logs are active
logger: vite.createLogger("warn", { prefix: "[react-router]" }),
});
}
reactRouterConfigLoader = await createConfigLoader({
rootDirectory,
watch: viteCommand === "serve",
});
await updatePluginContext();
Object.assign(
process.env,
vite.loadEnv(
viteConfigEnv.mode,
ctx.rootDirectory,
// We override default prefix of "VITE_" with a blank string since
// we're targeting the server, so we want to load all environment
// variables, not just those explicitly marked for the client
""
)
);
let baseRollupOptions = {
// Silence Rollup "use client" warnings
// Adapted from https://github.com/vitejs/vite-plugin-react/pull/144
onwarn(warning, defaultHandler) {
if (
warning.code === "MODULE_LEVEL_DIRECTIVE" &&
warning.message.includes("use client")
) {
return;
}
if (viteUserConfig.build?.rollupOptions?.onwarn) {
viteUserConfig.build.rollupOptions.onwarn(
warning,
defaultHandler
);
} else {
defaultHandler(warning);
}
},
} satisfies Vite.BuildOptions["rollupOptions"];
return {
__reactRouterPluginContext: ctx,
appType:
viteCommand === "serve" &&
viteConfigEnv.mode === "production" &&
ctx.reactRouterConfig.ssr === false
? "spa"
: "custom",
ssr: {
external: ssrExternals,
resolve: {
conditions:
viteCommand === "build"
? viteServerConditions
: ["development", ...viteServerConditions],
externalConditions:
viteCommand === "build"
? viteServerConditions
: ["development", ...viteServerConditions],
},
},
optimizeDeps: {
entries: ctx.reactRouterConfig.future.unstable_optimizeDeps
? [
ctx.entryClientFilePath,
...Object.values(ctx.reactRouterConfig.routes).map((route) =>
path.join(ctx.reactRouterConfig.appDirectory, route.file)
),
]
: [],
include: [
// Pre-bundle React dependencies to avoid React duplicates,
// even if React dependencies are not direct dependencies.
// https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
"react",
"react/jsx-runtime",
"react/jsx-dev-runtime",
"react-dom",
"react-dom/client",
// Pre-bundle router dependencies to avoid router duplicates.
// Mismatching routers cause `Error: You must render this element inside a <Remix> element`.
"react-router",
"react-router/dom",
// Check to avoid "Failed to resolve dependency: react-router-dom, present in 'optimizeDeps.include'"
...(hasDependency("react-router-dom")
? ["react-router-dom"]
: []),
],
},
esbuild: {
jsx: "automatic",
jsxDev: viteCommand !== "build",
},
resolve: {
dedupe: [
// https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
"react",
"react-dom",
// see description for `optimizeDeps.include`
"react-router",
"react-router/dom",
"react-router-dom",
],
conditions:
viteCommand === "build"
? viteClientConditions
: ["development", ...viteClientConditions],
},
base: viteUserConfig.base,
// When consumer provides an allow list for files that can be read by
// the server, ensure that the default entry files are included.
// If we don't do this and a default entry file is used, the server
// will throw an error that the file is not allowed to be read.
// https://vitejs.dev/config/server-options#server-fs-allow
server: viteUserConfig.server?.fs?.allow
? { fs: { allow: defaultEntries } }
: undefined,
// Vite config options for building
...(viteCommand === "build"
? {
build: {
cssMinify: viteUserConfig.build?.cssMinify ?? true,
...(!viteConfigEnv.isSsrBuild
? {
manifest: true,
outDir: getClientBuildDirectory(ctx.reactRouterConfig),
rollupOptions: {
...baseRollupOptions,
preserveEntrySignatures: "exports-only",
input: [
ctx.entryClientFilePath,
...Object.values(ctx.reactRouterConfig.routes).map(
(route) =>
`${path.resolve(
ctx.reactRouterConfig.appDirectory,
route.file
)}${BUILD_CLIENT_ROUTE_QUERY_STRING}`
),
],
},
}
: {
// We move SSR-only assets to client assets. Note that the
// SSR build can also emit code-split JS files (e.g. by
// dynamic import) under the same assets directory
// regardless of "ssrEmitAssets" option, so we also need to
// keep these JS files have to be kept as-is.
ssrEmitAssets: true,
copyPublicDir: false, // Assets in the public directory are only used by the client
manifest: true, // We need the manifest to detect SSR-only assets
outDir: getServerBuildDirectory(ctx),
rollupOptions: {
...baseRollupOptions,
preserveEntrySignatures: "exports-only",
input:
viteUserConfig.build?.rollupOptions?.input ??
virtual.serverBuild.id,
output: {
entryFileNames:
ctx.reactRouterConfig.serverBuildFile,
format: ctx.reactRouterConfig.serverModuleFormat,
},
},
}),
},
}
: undefined),
// Vite config options for SPA preview mode
...(viteCommand === "serve" && ctx.reactRouterConfig.ssr === false
? {
build: {
manifest: true,
outDir: getClientBuildDirectory(ctx.reactRouterConfig),
},
}
: undefined),
};
},
async configResolved(resolvedViteConfig) {
await initEsModuleLexer;
viteConfig = resolvedViteConfig;
invariant(viteConfig);
// We load the same Vite config file again for the child compiler so
// that both parent and child compiler's plugins have independent state.
// If we re-used the `viteUserConfig.plugins` array for the child
// compiler, it could lead to mutating shared state between plugin
// instances in unexpected ways, e.g. during `vite build` the
// `configResolved` plugin hook would be called with `command = "build"`
// by parent and then `command = "serve"` by child, which some plugins
// may respond to by updating state referenced by the parent.
if (!viteConfig.configFile) {
throw new Error(
"The React Router Vite plugin requires the use of a Vite config file"
);
}
let vite = getVite();
let childCompilerConfigFile = await vite.loadConfigFromFile(
{
command: viteConfig.command,
mode: viteConfig.mode,
isSsrBuild: ctx.isSsrBuild,
},
viteConfig.configFile
);
invariant(
childCompilerConfigFile,
"Vite config file was unable to be resolved for React Router child compiler"
);
// Validate that commonly used Rollup plugins that need to run before
// ours are in the correct order. This is because Rollup plugins can't
// set `enforce: "pre"` like Vite plugins can. Explicitly validating
// this provides a much nicer developer experience.
let rollupPrePlugins = [
{ pluginName: "@mdx-js/rollup", displayName: "@mdx-js/rollup" },
];
for (let prePlugin of rollupPrePlugins) {
let prePluginIndex = pluginIndex(prePlugin.pluginName);
if (
prePluginIndex >= 0 &&
prePluginIndex > pluginIndex("react-router")
) {
throw new Error(
`The "${prePlugin.displayName}" plugin should be placed before the React Router plugin in your Vite config file`
);
}
}
viteChildCompiler = await vite.createServer({
...viteUserConfig,
mode: viteConfig.mode,
server: {
watch: viteConfig.command === "build" ? null : undefined,
preTransformRequests: false,
hmr: false,
},
configFile: false,
envFile: false,
plugins: [
...(childCompilerConfigFile.config.plugins ?? [])
.flat()
// Exclude this plugin from the child compiler to prevent an
// infinite loop (plugin creates a child compiler with the same
// plugin that creates another child compiler, repeat ad
// infinitum), and to prevent the manifest from being written to
// disk from the child compiler. This is important in the
// production build because the child compiler is a Vite dev
// server and will generate incorrect manifests.
.filter(
(plugin) =>
typeof plugin === "object" &&
plugin !== null &&