-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
plugin.ts
1996 lines (1785 loc) · 63.8 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,
createRequestHandler,
} 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 omit from "lodash/omit";
import colors from "picocolors";
import { type RouteManifestEntry, type RouteManifest } from "../config/routes";
import {
type AppConfig as RemixEsbuildUserConfig,
type RemixConfig as ResolvedRemixEsbuildConfig,
resolveConfig as resolveCommonConfig,
findConfig,
} from "../config";
import { type Manifest as RemixManifest } from "../manifest";
import invariant from "../invariant";
import {
type NodeRequestHandler,
fromNodeRequest,
toNodeRequest,
} from "./node-adapter";
import { getStylesForUrl, isCssModulesFile } from "./styles";
import * as VirtualModule from "./vmod";
import { resolveFileUrl } from "./resolve-file-url";
import { combineURLs } from "./combine-urls";
import { removeExports } from "./remove-exports";
import { importViteEsmSync, preloadViteEsm } from "./import-vite-esm-sync";
import * as ViteNode from "./vite-node";
export async function resolveViteConfig({
configFile,
mode,
root,
}: {
configFile?: string;
mode?: string;
root: string;
}) {
let vite = await import("vite");
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 extractRemixPluginContext(
viteConfig: Vite.ResolvedConfig
) {
return viteConfig["__remixPluginContext" as keyof typeof viteConfig] as
| RemixPluginContext
| undefined;
}
export async function loadVitePluginContext({
configFile,
root,
}: {
configFile?: string;
root?: string;
}) {
if (!root) {
root = process.env.REMIX_ROOT || process.cwd();
}
configFile =
configFile ??
findConfig(root, "vite.config", [
".ts",
".cts",
".mts",
".js",
".cjs",
".mjs",
]);
// V3 TODO: Vite config should not be optional
if (!configFile) {
return;
}
let viteConfig = await resolveViteConfig({ configFile, root });
return await extractRemixPluginContext(viteConfig);
}
const supportedRemixEsbuildConfigKeys = [
"appDirectory",
"future",
"ignoredRouteFiles",
"routes",
"serverModuleFormat",
] as const satisfies ReadonlyArray<keyof RemixEsbuildUserConfig>;
type SupportedRemixEsbuildUserConfig = Pick<
RemixEsbuildUserConfig,
typeof supportedRemixEsbuildConfigKeys[number]
>;
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 = "?__remix-build-client-route";
// Only expose a subset of route properties to the "serverBundles" function
const branchRouteProperties = [
"id",
"path",
"file",
"index",
] as const satisfies ReadonlyArray<keyof RouteManifestEntry>;
type BranchRoute = Pick<
RouteManifestEntry,
typeof branchRouteProperties[number]
>;
export const configRouteToBranchRoute = (
configRoute: RouteManifestEntry
): BranchRoute => pick(configRoute, branchRouteProperties);
export type ServerBundlesFunction = (args: {
branch: BranchRoute[];
}) => string | Promise<string>;
type BaseBuildManifest = {
routes: RouteManifest;
};
type DefaultBuildManifest = BaseBuildManifest & {
serverBundles?: never;
routeIdToServerBundleId?: never;
};
export type ServerBundlesBuildManifest = BaseBuildManifest & {
serverBundles: {
[serverBundleId: string]: {
id: string;
file: string;
};
};
routeIdToServerBundleId: Record<string, string>;
};
export type BuildManifest = DefaultBuildManifest | ServerBundlesBuildManifest;
const excludedRemixConfigPresetKeys = [
"presets",
] as const satisfies ReadonlyArray<keyof VitePluginConfig>;
type ExcludedRemixConfigPresetKey =
typeof excludedRemixConfigPresetKeys[number];
type RemixConfigPreset = Omit<VitePluginConfig, ExcludedRemixConfigPresetKey>;
export type Preset = {
name: string;
remixConfig?: (args: {
remixUserConfig: VitePluginConfig;
}) => RemixConfigPreset | Promise<RemixConfigPreset>;
remixConfigResolved?: (args: {
remixConfig: ResolvedVitePluginConfig;
}) => void | Promise<void>;
};
export type VitePluginConfig = SupportedRemixEsbuildUserConfig & {
/**
* The react router app basename. Defaults to `"/"`.
*/
basename?: string;
/**
* The path to the build directory, relative to the project. Defaults to
* `"build"`.
*/
buildDirectory?: string;
/**
* A function that is called after the full Remix build is complete.
*/
buildEnd?: BuildEndHook;
/**
* Whether to write a `"manifest.json"` file to the build directory.`
* Defaults to `false`.
*/
manifest?: boolean;
/**
* An array of Remix config presets to ease integration with other platforms
* and tools.
*/
presets?: Array<Preset>;
/**
* 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.
*/
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`.
*/
ssr?: boolean;
};
type BuildEndHook = (args: {
buildManifest: BuildManifest | undefined;
remixConfig: ResolvedVitePluginConfig;
viteConfig: Vite.ResolvedConfig;
}) => void | Promise<void>;
export type ResolvedVitePluginConfig = Readonly<
Pick<
ResolvedRemixEsbuildConfig,
"appDirectory" | "future" | "publicPath" | "routes" | "serverModuleFormat"
> & {
basename: string;
buildDirectory: string;
buildEnd?: BuildEndHook;
manifest: boolean;
publicPath: string; // derived from Vite's `base` config
serverBuildFile: string;
serverBundles?: ServerBundlesFunction;
ssr: boolean;
}
>;
export type ServerBundleBuildConfig = {
routes: RouteManifest;
serverBundleId: string;
};
type RemixPluginSsrBuildContext =
| {
isSsrBuild: false;
getRemixServerManifest?: never;
serverBundleBuildConfig?: never;
}
| {
isSsrBuild: true;
getRemixServerManifest: () => Promise<RemixManifest>;
serverBundleBuildConfig: ServerBundleBuildConfig | null;
};
export type RemixPluginContext = RemixPluginSsrBuildContext & {
rootDirectory: string;
entryClientFilePath: string;
entryServerFilePath: string;
remixConfig: ResolvedVitePluginConfig;
viteManifestEnabled: boolean;
};
let serverBuildId = VirtualModule.id("server-build");
let serverManifestId = VirtualModule.id("server-manifest");
let browserManifestId = VirtualModule.id("browser-manifest");
let hmrRuntimeId = VirtualModule.id("hmr-runtime");
let injectHmrRuntimeId = VirtualModule.id("inject-hmr-runtime");
const resolveRelativeRouteFilePath = (
route: RouteManifestEntry,
remixConfig: ResolvedVitePluginConfig
) => {
let vite = importViteEsmSync();
let file = route.file;
let fullPath = path.resolve(remixConfig.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 = (
ctx: RemixPluginContext,
viteManifest: Vite.Manifest,
absoluteFilePath: string
) => {
let vite = importViteEsmSync();
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 getRemixManifestBuildAssets = (
ctx: RemixPluginContext,
viteManifest: Vite.Manifest,
entryFilePath: string,
prependedAssetFilePaths: string[] = []
): RemixManifest["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.remixConfig.publicPath}${entryChunk.file}`,
imports:
dedupe(chunks.flatMap((e) => e.imports ?? [])).map((imported) => {
return `${ctx.remixConfig.publicPath}${viteManifest[imported].file}`;
}) ?? [],
css:
dedupe(chunks.flatMap((e) => e.css ?? [])).map((href) => {
return `${ctx.remixConfig.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: RemixPluginContext
): Promise<Record<string, string[]>> => {
let entries = await Promise.all(
Object.entries(ctx.remixConfig.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: RemixPluginContext,
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.remixConfig.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 (
!("__remixServerBundleBuildConfig" in viteUserConfig) ||
!viteUserConfig.__remixServerBundleBuildConfig
) {
return null;
}
return viteUserConfig.__remixServerBundleBuildConfig as ServerBundleBuildConfig;
};
export let getServerBuildDirectory = (ctx: RemixPluginContext) =>
path.join(
ctx.remixConfig.buildDirectory,
"server",
...(ctx.serverBundleBuildConfig
? [ctx.serverBundleBuildConfig.serverBundleId]
: [])
);
let getClientBuildDirectory = (remixConfig: ResolvedVitePluginConfig) =>
path.join(remixConfig.buildDirectory, "client");
let defaultEntriesDir = path.resolve(__dirname, "..", "config", "defaults");
let defaultEntries = fse
.readdirSync(defaultEntriesDir)
.map((filename) => path.join(defaultEntriesDir, filename));
invariant(defaultEntries.length > 0, "No default entries found");
let mergeRemixConfig = (...configs: VitePluginConfig[]): VitePluginConfig => {
let reducer = (
configA: VitePluginConfig,
configB: VitePluginConfig
): VitePluginConfig => {
let mergeRequired = (key: keyof VitePluginConfig) =>
configA[key] !== undefined && configB[key] !== undefined;
return {
...configA,
...configB,
...(mergeRequired("buildEnd")
? {
buildEnd: async (...args) => {
await Promise.all([
configA.buildEnd?.(...args),
configB.buildEnd?.(...args),
]);
},
}
: {}),
...(mergeRequired("future")
? {
future: {
...configA.future,
...configB.future,
},
}
: {}),
...(mergeRequired("ignoredRouteFiles")
? {
ignoredRouteFiles: Array.from(
new Set([
...(configA.ignoredRouteFiles ?? []),
...(configB.ignoredRouteFiles ?? []),
])
),
}
: {}),
...(mergeRequired("presets")
? {
presets: [...(configA.presets ?? []), ...(configB.presets ?? [])],
}
: {}),
...(mergeRequired("routes")
? {
routes: async (...args) => {
let [routesA, routesB] = await Promise.all([
configA.routes?.(...args),
configB.routes?.(...args),
]);
return {
...routesA,
...routesB,
};
},
}
: {}),
};
};
return configs.reduce(reducer, {});
};
type MaybePromise<T> = T | Promise<T>;
let remixDevLoadContext: (
request: Request
) => MaybePromise<Record<string, unknown>> = () => ({});
export let setRemixDevLoadContext = (
loadContext: (request: Request) => MaybePromise<Record<string, unknown>>
) => {
remixDevLoadContext = loadContext;
};
// Inlined from https://github.com/jsdf/deep-freeze
let deepFreeze = (o: any) => {
Object.freeze(o);
let oIsFunction = typeof o === "function";
let hasOwnProp = Object.prototype.hasOwnProperty;
Object.getOwnPropertyNames(o).forEach(function (prop) {
if (
hasOwnProp.call(o, prop) &&
(oIsFunction
? prop !== "caller" && prop !== "callee" && prop !== "arguments"
: true) &&
o[prop] !== null &&
(typeof o[prop] === "object" || typeof o[prop] === "function") &&
!Object.isFrozen(o[prop])
) {
deepFreeze(o[prop]);
}
});
return o;
};
export type RemixVitePlugin = (config?: VitePluginConfig) => Vite.Plugin[];
export const remixVitePlugin: RemixVitePlugin = (remixUserConfig = {}) => {
// Prevent mutations to the user config
remixUserConfig = deepFreeze(remixUserConfig);
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 routesViteNodeContext: ViteNode.Context | null = null;
let ssrExternals = isInRemixMonorepo()
? [
// This is only needed within the Remix repo because these
// packages are linked to a directory outside of node_modules
// so Vite treats them as internal code by default.
"@remix-run/architect",
"@remix-run/cloudflare-pages",
"@remix-run/cloudflare-workers",
"@remix-run/cloudflare",
"@remix-run/css-bundle",
"@remix-run/deno",
"@remix-run/dev",
"@remix-run/express",
"@remix-run/netlify",
"@remix-run/node",
"@remix-run/react",
"@remix-run/serve",
"@remix-run/server-runtime",
]
: undefined;
// This is initialized by `updateRemixPluginContext` during Vite's `config`
// hook, so most of the code can assume this defined without null check.
// During dev, `updateRemixPluginContext` is called again on every config file
// change or route file addition/removal.
let ctx: RemixPluginContext;
/** Mutates `ctx` as a side-effect */
let updateRemixPluginContext = async ({
routeConfigChanged = false,
}: {
routeConfigChanged?: boolean;
} = {}): Promise<void> => {
let remixConfigPresets: VitePluginConfig[] = (
await Promise.all(
(remixUserConfig.presets ?? []).map(async (preset) => {
if (!preset.name) {
throw new Error(
"Remix presets must have a `name` property defined."
);
}
if (!preset.remixConfig) {
return null;
}
let remixConfigPreset: VitePluginConfig = omit(
await preset.remixConfig({ remixUserConfig }),
excludedRemixConfigPresetKeys
);
return remixConfigPreset;
})
)
).filter(function isNotNull<T>(value: T | null): value is T {
return value !== null;
});
let defaults = {
basename: "/",
buildDirectory: "build",
manifest: false,
serverBuildFile: "index.js",
ssr: true,
} as const satisfies Partial<VitePluginConfig>;
let resolvedRemixUserConfig = {
...defaults, // Default values should be completely overridden by user/preset config, not merged
...mergeRemixConfig(...remixConfigPresets, remixUserConfig),
};
let rootDirectory =
viteUserConfig.root ?? process.env.REMIX_ROOT ?? process.cwd();
let { basename, buildEnd, manifest, ssr } = resolvedRemixUserConfig;
let isSpaMode = !ssr;
// Only select the Remix esbuild config options that the Vite plugin uses
invariant(routesViteNodeContext);
let {
appDirectory,
entryClientFilePath,
entryServerFilePath,
future,
routes,
serverModuleFormat,
} = await resolveCommonConfig(
pick(resolvedRemixUserConfig, supportedRemixEsbuildConfigKeys),
{
rootDirectory,
isSpaMode,
vite: importViteEsmSync(),
routeConfigChanged,
viteUserConfig,
routesViteNodeContext,
}
);
let buildDirectory = path.resolve(
rootDirectory,
resolvedRemixUserConfig.buildDirectory
);
let { serverBuildFile, serverBundles } = resolvedRemixUserConfig;
let publicPath = viteUserConfig.base ?? "/";
if (
basename !== "/" &&
viteCommand === "serve" &&
!viteUserConfig.server?.middlewareMode &&
!basename.startsWith(publicPath)
) {
throw new Error(
"When using the Remix `basename` and the Vite `base` config, " +
"the `basename` config must begin with `base` for the default " +
"Vite dev server."
);
}
// Log warning for incompatible vite config flags
if (isSpaMode && serverBundles) {
console.warn(
colors.yellow(
colors.bold("⚠️ SPA Mode: ") +
"the `serverBundles` config is invalid with " +
"`ssr:false` and will be ignored`"
)
);
serverBundles = undefined;
}
let remixConfig: ResolvedVitePluginConfig = deepFreeze({
appDirectory,
basename,
buildDirectory,
buildEnd,
future,
manifest,
publicPath,
routes,
serverBuildFile,
serverBundles,
serverModuleFormat,
ssr,
});
for (let preset of remixUserConfig.presets ?? []) {
await preset.remixConfigResolved?.({ remixConfig });
}
let viteManifestEnabled = viteUserConfig.build?.manifest === true;
let ssrBuildCtx: RemixPluginSsrBuildContext =
viteConfigEnv.isSsrBuild && viteCommand === "build"
? {
isSsrBuild: true,
getRemixServerManifest: async () =>
(await generateRemixManifestsForBuild()).remixServerManifest,
serverBundleBuildConfig: getServerBundleBuildConfig(viteUserConfig),
}
: { isSsrBuild: false };
ctx = {
remixConfig,
rootDirectory,
entryClientFilePath,
entryServerFilePath,
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");
// v3 TODO:
// - Deprecate `ServerBuild.mode` once we officially stabilize vite and
// mark the old compiler as deprecated
// - Remove `ServerBuild.mode` in v3
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.remixConfig.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.remixConfig)
)
)};`;
})
.join("\n")}
/**
* \`mode\` is only relevant for the old Remix compiler but
* is included here to satisfy the \`ServerBuild\` typings.
*/
export const mode = ${JSON.stringify(viteConfig.mode)};
export { default as assets } from ${JSON.stringify(serverManifestId)};
export const assetsBuildDirectory = ${JSON.stringify(
path.relative(
ctx.rootDirectory,
getClientBuildDirectory(ctx.remixConfig)
)
)};
export const basename = ${JSON.stringify(ctx.remixConfig.basename)};
export const future = ${JSON.stringify(ctx.remixConfig.future)};
export const isSpaMode = ${!ctx.remixConfig.ssr};
export const publicPath = ${JSON.stringify(ctx.remixConfig.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 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 generateRemixManifestsForBuild = async (): Promise<{
remixBrowserManifest: RemixManifest;
remixServerManifest: RemixManifest;
}> => {
invariant(viteConfig);
let viteManifest = await loadViteManifest(
getClientBuildDirectory(ctx.remixConfig)
);
let entry = getRemixManifestBuildAssets(
ctx,
viteManifest,
ctx.entryClientFilePath
);
let browserRoutes: RemixManifest["routes"] = {};
let serverRoutes: RemixManifest["routes"] = {};
let routeManifestExports = await getRouteManifestModuleExports(
viteChildCompiler,
ctx
);
for (let [key, route] of Object.entries(ctx.remixConfig.routes)) {
let routeFilePath = path.join(ctx.remixConfig.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"),
...getRemixManifestBuildAssets(
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.remixConfig.publicPath}${manifestPath}`;
let nonFingerprintedValues = { url, version };
let remixBrowserManifest: RemixManifest = {
...fingerprintedValues,
...nonFingerprintedValues,
};
// Write the browser manifest to disk as part of the build process
await writeFileSafe(
path.join(getClientBuildDirectory(ctx.remixConfig), manifestPath),
`window.__remixManifest=${JSON.stringify(remixBrowserManifest)};`
);
// 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 remixServerManifest: RemixManifest = {
...remixBrowserManifest,
routes: serverRoutes,
};
return {
remixBrowserManifest,
remixServerManifest,
};
};
// In dev, the server and browser Remix manifests are the same
let getRemixManifestForDev = async (): Promise<RemixManifest> => {
let routes: RemixManifest["routes"] = {};
let routeManifestExports = await getRouteManifestModuleExports(
viteChildCompiler,
ctx
);
for (let [key, route] of Object.entries(ctx.remixConfig.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.remixConfig.publicPath,
`${resolveFileUrl(
ctx,
resolveRelativeRouteFilePath(route, ctx.remixConfig)