-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathplugin.ts
1549 lines (1388 loc) · 51.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 babel from "@babel/core";
import {
type ServerBuild,
unstable_setDevServerHooks as setDevServerHooks,
} from "@remix-run/server-runtime";
import {
init as initEsModuleLexer,
parse as esModuleLexer,
} from "es-module-lexer";
import jsesc from "jsesc";
import pick from "lodash/pick";
import colors from "picocolors";
import { type ConfigRoute, type RouteManifest } from "../config/routes";
import {
type AppConfig as RemixUserConfig,
type RemixConfig as ResolvedRemixConfig,
resolveConfig,
} from "../config";
import { type Manifest } from "../manifest";
import invariant from "../invariant";
import { createRequestHandler } from "./node/adapter";
import { getStylesForUrl, isCssModulesFile } from "./styles";
import * as VirtualModule from "./vmod";
import { resolveFileUrl } from "./resolve-file-url";
import { removeExports } from "./remove-exports";
import { replaceImportSpecifier } from "./replace-import-specifier";
import { importViteEsmSync, preloadViteEsm } from "./import-vite-esm-sync";
const supportedRemixConfigKeys = [
"appDirectory",
"assetsBuildDirectory",
"future",
"ignoredRouteFiles",
"publicPath",
"routes",
"serverModuleFormat",
] as const satisfies ReadonlyArray<keyof RemixUserConfig>;
type SupportedRemixConfigKey = typeof supportedRemixConfigKeys[number];
type SupportedRemixConfig = Pick<RemixUserConfig, SupportedRemixConfigKey>;
const SERVER_ONLY_ROUTE_EXPORTS = ["loader", "action", "headers"];
const CLIENT_ROUTE_EXPORTS = [
"clientAction",
"clientLoader",
"default",
"ErrorBoundary",
"handle",
"HydrateFallback",
"links",
"meta",
"shouldRevalidate",
];
const CLIENT_ROUTE_QUERY_STRING = "?client-route";
// We need to provide different JSDoc comments in some cases due to differences
// between the Remix config and the Vite plugin.
type RemixConfigJsdocOverrides = {
/**
* The path to the browser build, relative to the project root. Defaults to
* `"build/client"`.
*/
assetsBuildDirectory?: SupportedRemixConfig["assetsBuildDirectory"];
/**
* The URL prefix of the browser build with a trailing slash. Defaults to
* `"/"`. This is the path the browser will use to find assets.
*/
publicPath?: SupportedRemixConfig["publicPath"];
};
// Only expose a subset of route properties to the "serverBundles" function
const branchRouteProperties = [
"id",
"path",
"file",
"index",
] as const satisfies ReadonlyArray<keyof ConfigRoute>;
type BranchRoute = Pick<ConfigRoute, typeof branchRouteProperties[number]>;
export const configRouteToBranchRoute = (
configRoute: ConfigRoute
): BranchRoute => pick(configRoute, branchRouteProperties);
type ServerBundlesFunction = (args: {
branch: BranchRoute[];
}) => string | Promise<string>;
export type RemixVitePluginOptions = RemixConfigJsdocOverrides &
Omit<SupportedRemixConfig, keyof RemixConfigJsdocOverrides> & {
/**
* The path to the server build directory, relative to the project. This
* directory should be deployed to your server. Defaults to
* `"build/server"`.
*/
serverBuildDirectory?: string;
/**
* The file name of the server build output. This file
* should end in a `.js` extension and should be deployed to your server.
* Defaults to `"index.js"`.
*/
serverBuildFile?: string;
/**
* A function for assigning routes to different server bundles. This
* function should return a server bundle ID which will be used as the
* bundle's directory name within the server build directory.
*/
unstable_serverBundles?: ServerBundlesFunction;
/**
* Enable server-side rendering for your application. Disable to use Remix in
* "SPA Mode", which will request the `/` path at build-time and save it as
* an `index.html` file with your assets so your application can be deployed
* as a SPA without server-rendering. Default's to `true`.
*/
unstable_ssr?: boolean;
};
export type ResolvedRemixVitePluginConfig = Pick<
ResolvedRemixConfig,
| "appDirectory"
| "rootDirectory"
| "assetsBuildDirectory"
| "entryClientFilePath"
| "entryServerFilePath"
| "future"
| "isSpaMode"
| "publicPath"
| "relativeAssetsBuildDirectory"
| "routes"
| "serverModuleFormat"
> & {
serverBuildDirectory: string;
serverBuildFile: string;
serverBundles?: ServerBundlesFunction;
};
export type ServerBuildConfig = {
routes: RouteManifest;
serverBuildDirectory: string;
};
let serverBuildId = VirtualModule.id("server-build");
let serverManifestId = VirtualModule.id("server-manifest");
let browserManifestId = VirtualModule.id("browser-manifest");
let remixReactProxyId = VirtualModule.id("remix-react-proxy");
let hmrRuntimeId = VirtualModule.id("hmr-runtime");
let injectHmrRuntimeId = VirtualModule.id("inject-hmr-runtime");
const resolveRelativeRouteFilePath = (
route: ConfigRoute,
pluginConfig: ResolvedRemixVitePluginConfig
) => {
let vite = importViteEsmSync();
let file = route.file;
let fullPath = path.resolve(pluginConfig.appDirectory, file);
return vite.normalizePath(fullPath);
};
let vmods = [serverBuildId, serverManifestId, browserManifestId];
const invalidateVirtualModules = (viteDevServer: Vite.ViteDevServer) => {
vmods.forEach((vmod) => {
let mod = viteDevServer.moduleGraph.getModuleById(
VirtualModule.resolve(vmod)
);
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 = (
pluginConfig: ResolvedRemixVitePluginConfig,
viteManifest: Vite.Manifest,
absoluteFilePath: string
) => {
let vite = importViteEsmSync();
let rootRelativeFilePath = vite.normalizePath(
path.relative(pluginConfig.rootDirectory, absoluteFilePath)
);
let entryChunk =
viteManifest[rootRelativeFilePath + 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 resolveBuildAssetPaths = (
pluginConfig: ResolvedRemixVitePluginConfig,
viteManifest: Vite.Manifest,
entryFilePath: string,
prependedAssetFilePaths: string[] = []
): Manifest["entry"] & { css: string[] } => {
let entryChunk = resolveChunk(pluginConfig, viteManifest, entryFilePath);
// This is here to support prepending client entry assets to the root route
let prependedAssetChunks = prependedAssetFilePaths.map((filePath) =>
resolveChunk(pluginConfig, viteManifest, filePath)
);
let chunks = resolveDependantChunks(viteManifest, [
...prependedAssetChunks,
entryChunk,
]);
return {
module: `${pluginConfig.publicPath}${entryChunk.file}${CLIENT_ROUTE_QUERY_STRING}`,
imports:
dedupe(chunks.flatMap((e) => e.imports ?? [])).map((imported) => {
return `${pluginConfig.publicPath}${viteManifest[imported].file}`;
}) ?? [],
css:
dedupe(chunks.flatMap((e) => e.css ?? [])).map((href) => {
return `${pluginConfig.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;
}
if (chunk.imports) {
for (let importKey of chunk.imports) {
walk(viteManifest[importKey]);
}
}
chunks.add(chunk);
}
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,
pluginConfig: ResolvedRemixVitePluginConfig
): Promise<Record<string, string[]>> => {
let entries = await Promise.all(
Object.entries(pluginConfig.routes).map(async ([key, route]) => {
let sourceExports = await getRouteModuleExports(
viteChildCompiler,
pluginConfig,
route.file
);
return [key, sourceExports] as const;
})
);
return Object.fromEntries(entries);
};
const getRouteModuleExports = async (
viteChildCompiler: Vite.ViteDevServer | null,
pluginConfig: ResolvedRemixVitePluginConfig,
routeFile: 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(pluginConfig.appDirectory, routeFile);
let url = resolveFileUrl(pluginConfig, 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(),
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);
if (exportNames.length === 0) {
console.log("[getRouteMetadata:empty]", { routeFile, code });
}
return exportNames;
};
const getViteMajorVersion = (): number => {
let vitePkg = require("vite/package.json");
return parseInt(vitePkg.version.split(".")[0]!);
};
export type RemixVitePlugin = (
options?: RemixVitePluginOptions
) => Vite.Plugin[];
export const remixVitePlugin: RemixVitePlugin = (options = {}) => {
let viteCommand: Vite.ResolvedConfig["command"];
let viteUserConfig: Vite.UserConfig;
let viteConfig: Vite.ResolvedConfig | undefined;
let isViteV4 = getViteMajorVersion() === 4;
let cssModulesManifest: Record<string, string> = {};
let ssrBuildContext:
| { isSsrBuild: false }
| { isSsrBuild: true; getManifest: () => Promise<Manifest> };
let viteChildCompiler: Vite.ViteDevServer | null = null;
let cachedPluginConfig: ResolvedRemixVitePluginConfig | undefined;
let resolveServerBuildConfig = (): ServerBuildConfig | null => {
if (
!("__remixServerBuildConfig" in viteUserConfig) ||
!viteUserConfig.__remixServerBuildConfig
) {
return null;
}
let { routes, serverBuildDirectory } =
viteUserConfig.__remixServerBuildConfig as ServerBuildConfig;
// Ensure extra config values can't sneak through
return { routes, serverBuildDirectory };
};
let resolvePluginConfig =
async (): Promise<ResolvedRemixVitePluginConfig> => {
let defaults = {
assetsBuildDirectory: "build/client",
serverBuildDirectory: "build/server",
serverBuildFile: "index.js",
publicPath: "/",
unstable_ssr: true,
} as const satisfies Partial<RemixVitePluginOptions>;
let pluginConfig = {
...defaults,
...options,
};
let rootDirectory =
viteUserConfig.root ?? process.env.REMIX_ROOT ?? process.cwd();
let isSpaMode = pluginConfig.unstable_ssr === false;
let resolvedRemixConfig = await resolveConfig(
pick(pluginConfig, supportedRemixConfigKeys),
{
rootDirectory,
isSpaMode,
}
);
// Only select the Remix config options that the Vite plugin uses
let {
appDirectory,
assetsBuildDirectory,
entryClientFilePath,
publicPath,
routes,
entryServerFilePath,
serverBuildDirectory,
serverBuildFile,
unstable_serverBundles,
serverModuleFormat,
relativeAssetsBuildDirectory,
future,
} = {
...pluginConfig,
...resolvedRemixConfig,
...resolveServerBuildConfig(),
};
// Log warning for incompatible vite config flags
if (isSpaMode && unstable_serverBundles) {
console.warn(
colors.yellow(
colors.bold("⚠️ SPA Mode: ") +
"the `unstable_serverBundles` config is invalid with " +
"`unstable_ssr:false` and will be ignored`"
)
);
unstable_serverBundles = undefined;
}
return {
appDirectory,
rootDirectory,
assetsBuildDirectory,
entryClientFilePath,
publicPath,
routes,
entryServerFilePath,
serverBuildDirectory,
serverBuildFile,
serverBundles: unstable_serverBundles,
serverModuleFormat,
isSpaMode,
relativeAssetsBuildDirectory,
future,
};
};
let getServerEntry = async () => {
let pluginConfig = await resolvePluginConfig();
return `
import * as entryServer from ${JSON.stringify(
resolveFileUrl(pluginConfig, pluginConfig.entryServerFilePath)
)};
${Object.keys(pluginConfig.routes)
.map((key, index) => {
let route = pluginConfig.routes[key]!;
return `import * as route${index} from ${JSON.stringify(
resolveFileUrl(
pluginConfig,
resolveRelativeRouteFilePath(route, pluginConfig)
)
)};`;
})
.join("\n")}
export { default as assets } from ${JSON.stringify(serverManifestId)};
export const assetsBuildDirectory = ${JSON.stringify(
pluginConfig.relativeAssetsBuildDirectory
)};
export const future = ${JSON.stringify(pluginConfig.future)};
export const isSpaMode = ${pluginConfig.isSpaMode === true};
export const publicPath = ${JSON.stringify(pluginConfig.publicPath)};
export const entry = { module: entryServer };
export const routes = {
${Object.keys(pluginConfig.routes)
.map((key, index) => {
let route = pluginConfig.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 manifestPath = isViteV4
? "manifest.json"
: path.join(".vite", "manifest.json");
let manifestContents = await fse.readFile(
path.resolve(directory, manifestPath),
"utf-8"
);
return JSON.parse(manifestContents) as Vite.Manifest;
};
let createBuildManifest = async (): Promise<Manifest> => {
let pluginConfig = await resolvePluginConfig();
let viteManifest = await loadViteManifest(
pluginConfig.assetsBuildDirectory
);
let entry = resolveBuildAssetPaths(
pluginConfig,
viteManifest,
pluginConfig.entryClientFilePath
);
let routes: Manifest["routes"] = {};
let routeManifestExports = await getRouteManifestModuleExports(
viteChildCompiler,
pluginConfig
);
for (let [key, route] of Object.entries(pluginConfig.routes)) {
let routeFilePath = path.join(pluginConfig.appDirectory, route.file);
let sourceExports = routeManifestExports[key];
let isRootRoute = route.parentId === undefined;
routes[key] = {
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"),
...resolveBuildAssetPaths(
pluginConfig,
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 ? [pluginConfig.entryClientFilePath] : []
),
};
}
let fingerprintedValues = { entry, routes };
let version = getHash(JSON.stringify(fingerprintedValues), 8);
let manifestPath = `assets/manifest-${version}.js`;
let url = `${pluginConfig.publicPath}${manifestPath}`;
let nonFingerprintedValues = { url, version };
let manifest: Manifest = {
...fingerprintedValues,
...nonFingerprintedValues,
};
await writeFileSafe(
path.join(pluginConfig.assetsBuildDirectory, manifestPath),
`window.__remixManifest=${JSON.stringify(manifest)};`
);
return manifest;
};
let getDevManifest = async (): Promise<Manifest> => {
let pluginConfig = await resolvePluginConfig();
let routes: Manifest["routes"] = {};
let routeManifestExports = await getRouteManifestModuleExports(
viteChildCompiler,
pluginConfig
);
for (let [key, route] of Object.entries(pluginConfig.routes)) {
let sourceExports = routeManifestExports[key];
routes[key] = {
id: route.id,
parentId: route.parentId,
path: route.path,
index: route.index,
caseSensitive: route.caseSensitive,
module: `${resolveFileUrl(
pluginConfig,
resolveRelativeRouteFilePath(route, pluginConfig)
)}${CLIENT_ROUTE_QUERY_STRING}`,
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: VirtualModule.url(browserManifestId),
hmr: {
runtime: VirtualModule.url(injectHmrRuntimeId),
},
entry: {
module: resolveFileUrl(pluginConfig, pluginConfig.entryClientFilePath),
imports: [],
},
routes,
};
};
return [
{
name: "remix",
config: async (_viteUserConfig, viteConfigEnv) => {
// Preload Vite's ESM build up-front as soon as we're in an async context
await preloadViteEsm();
// Ensure sync import of Vite works after async preload
let vite = importViteEsmSync();
viteUserConfig = _viteUserConfig;
viteCommand = viteConfigEnv.command;
let pluginConfig = await resolvePluginConfig();
cachedPluginConfig = pluginConfig;
Object.assign(
process.env,
vite.loadEnv(
viteConfigEnv.mode,
pluginConfig.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 isSsrBuild =
"ssrBuild" in viteConfigEnv &&
typeof viteConfigEnv.ssrBuild === "boolean"
? viteConfigEnv.ssrBuild // Vite v4 back compat
: viteConfigEnv.isSsrBuild;
return {
__remixPluginResolvedConfig: pluginConfig,
appType: "custom",
experimental: { hmrPartialAccept: true },
optimizeDeps: {
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/client",
// Pre-bundle Remix dependencies to avoid Remix router duplicates.
// Our remix-remix-react-proxy plugin does not process default client and
// server entry files since those come from within `node_modules`.
// That means that before Vite pre-bundles dependencies (e.g. first time dev server is run)
// mismatching Remix routers cause `Error: You must render this element inside a <Remix> element`.
"@remix-run/react",
// For some reason, the `vite-dotenv` integration test consistently fails on webkit
// with `504 (Outdated Optimize Dep)` from Vite unless `@remix-run/node` is included
// in `optimizeDeps.include`. 🤷
// This could be caused by how we copy `node_modules/` into integration test fixtures,
// so maybe this will be unnecessary once we switch to pnpm
"@remix-run/node",
],
},
esbuild: {
jsx: "automatic",
jsxDev: viteCommand !== "build",
},
resolve: {
dedupe: [
// https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
"react",
"react-dom",
// see description for `@remix-run/react` in `optimizeDeps.include`
"@remix-run/react",
],
},
...(viteCommand === "build" && {
base: pluginConfig.publicPath,
build: {
...viteUserConfig.build,
...(!isSsrBuild
? {
manifest: true,
outDir: pluginConfig.assetsBuildDirectory,
rollupOptions: {
...viteUserConfig.build?.rollupOptions,
preserveEntrySignatures: "exports-only",
input: [
pluginConfig.entryClientFilePath,
...Object.values(pluginConfig.routes).map(
(route) =>
`${path.resolve(
pluginConfig.appDirectory,
route.file
)}${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: pluginConfig.serverBuildDirectory,
rollupOptions: {
...viteUserConfig.build?.rollupOptions,
preserveEntrySignatures: "exports-only",
input: serverBuildId,
output: {
entryFileNames: pluginConfig.serverBuildFile,
format: pluginConfig.serverModuleFormat,
},
},
}),
},
}),
};
},
async configResolved(resolvedViteConfig) {
await initEsModuleLexer;
viteConfig = resolvedViteConfig;
ssrBuildContext =
viteConfig.build.ssr && viteCommand === "build"
? { isSsrBuild: true, getManifest: createBuildManifest }
: { isSsrBuild: false };
// 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 Remix Vite plugin requires the use of a Vite config file"
);
}
let vite = importViteEsmSync();
let childCompilerConfigFile = await vite.loadConfigFromFile(
{
command: viteConfig.command,
mode: viteConfig.mode,
...(isViteV4
? { ssrBuild: ssrBuildContext.isSsrBuild }
: { isSsrBuild: ssrBuildContext.isSsrBuild }),
},
viteConfig.configFile
);
invariant(
childCompilerConfigFile,
"Vite config file was unable to be resolved for Remix child compiler"
);
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 &&
"name" in plugin &&
plugin.name !== "remix" &&
plugin.name !== "remix-hmr-updates"
),
],
});
await viteChildCompiler.pluginContainer.buildStart({});
},
async transform(code, id) {
if (isCssModulesFile(id)) {
cssModulesManifest[id] = code;
}
if (id.endsWith(CLIENT_ROUTE_QUERY_STRING)) {
invariant(cachedPluginConfig);
let routeModuleId = id.replace(CLIENT_ROUTE_QUERY_STRING, "");
let sourceExports = await getRouteModuleExports(
viteChildCompiler,
cachedPluginConfig,
routeModuleId
);
let routeFileName = path.basename(routeModuleId);
let clientExports = sourceExports
.filter((exportName) => CLIENT_ROUTE_EXPORTS.includes(exportName))
.join(", ");
return `export { ${clientExports} } from "./${routeFileName}";`;
}
},
buildStart() {
invariant(viteConfig);
if (
viteCommand === "build" &&
viteConfig.mode === "production" &&
!viteConfig.build.ssr &&
viteConfig.build.sourcemap
) {
viteConfig.logger.warn(
colors.yellow(
"\n" +
colors.bold(" ⚠️ Source maps are enabled in production\n") +
[
"This makes your server code publicly",
"visible in the browser. This is highly",
"discouraged! If you insist, ensure that",
"you are using environment variables for",
"secrets and not hard-coding them in",
"your source code.",
]
.map((line) => " " + line)
.join("\n") +
"\n"
)
);
}
},
configureServer(viteDevServer) {
setDevServerHooks({
// Give the request handler access to the critical CSS in dev to avoid a
// flash of unstyled content since Vite injects CSS file contents via JS
getCriticalCss: async (build, url) => {
invariant(cachedPluginConfig);
return getStylesForUrl(
viteDevServer,
cachedPluginConfig,
cssModulesManifest,
build,
url
);
},
// If an error is caught within the request handler, let Vite fix the
// stack trace so it maps back to the actual source code
processRequestError: (error) => {
if (error instanceof Error) {
viteDevServer.ssrFixStacktrace(error);
}
},
});
// We cache the pluginConfig here to make sure we're only invalidating virtual modules when necessary.
// This requires a separate cache from `cachedPluginConfig`, which is updated by remix-hmr-updates. If
// we shared the cache, it would already be refreshed by remix-hmr-updates at this point, and we'd
// have no way of comparing against the cache to know if the virtual modules need to be invalidated.
let previousPluginConfig: ResolvedRemixVitePluginConfig | undefined;
return () => {
viteDevServer.middlewares.use(async (_req, _res, next) => {
try {
let pluginConfig = await resolvePluginConfig();
if (
JSON.stringify(pluginConfig) !==
JSON.stringify(previousPluginConfig)
) {
previousPluginConfig = pluginConfig;
invalidateVirtualModules(viteDevServer);
}
next();
} catch (error) {
next(error);
}
});
// Let user servers handle SSR requests in middleware mode,
// otherwise the Vite plugin will handle the request
if (!viteDevServer.config.server.middlewareMode) {
viteDevServer.middlewares.use(async (req, res, next) => {
try {
let build = (await viteDevServer.ssrLoadModule(
serverBuildId
)) as ServerBuild;
let handle = createRequestHandler(build, {
mode: "development",
});
await handle(req, res);
} catch (error) {
next(error);
}
});
}
};
},
writeBundle: {
// After the SSR build is finished, we inspect the Vite manifest for
// the SSR build and move server-only assets to client assets directory
async handler() {
if (!ssrBuildContext.isSsrBuild) {
return;
}
invariant(cachedPluginConfig);
invariant(viteConfig);
let {
assetsBuildDirectory,
serverBuildDirectory,
serverBuildFile,
rootDirectory,
} = cachedPluginConfig;
let ssrViteManifest = await loadViteManifest(serverBuildDirectory);
let clientViteManifest = await loadViteManifest(assetsBuildDirectory);
let clientAssetPaths = new Set(
Object.values(clientViteManifest).flatMap(
(chunk) => chunk.assets ?? []
)
);
let ssrAssetPaths = new Set(
Object.values(ssrViteManifest).flatMap(
(chunk) => chunk.assets ?? []
)
);
// We only move assets that aren't in the client build, otherwise we
// remove them. These assets only exist because we explicitly set
// `ssrEmitAssets: true` in the SSR Vite config. These assets
// typically wouldn't exist by default, which is why we assume it's
// safe to remove them. We're aiming for a clean build output so that
// unnecessary assets don't get deployed alongside the server code.
let movedAssetPaths: string[] = [];
for (let ssrAssetPath of ssrAssetPaths) {
let src = path.join(serverBuildDirectory, ssrAssetPath);
if (!clientAssetPaths.has(ssrAssetPath)) {
let dest = path.join(assetsBuildDirectory, ssrAssetPath);
await fse.move(src, dest);
movedAssetPaths.push(dest);
} else {
await fse.remove(src);
}
}
// We assume CSS files from the SSR build are unnecessary and remove
// them for the same reasons as above.
let ssrCssPaths = Object.values(ssrViteManifest).flatMap(
(chunk) => chunk.css ?? []
);
await Promise.all(
ssrCssPaths.map((cssPath) =>
fse.remove(path.join(serverBuildDirectory, cssPath))
)
);
if (movedAssetPaths.length) {
viteConfig.logger.info(
[