-
-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathsplit-route-modules-test.ts
550 lines (492 loc) · 19.3 KB
/
split-route-modules-test.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
import { test, expect, type Page } from "@playwright/test";
import getPort from "get-port";
import dedent from "dedent";
import {
createProject,
build,
reactRouterServe,
viteConfig,
reactRouterConfig,
} from "./helpers/vite.js";
const js = String.raw;
const files = {
"app/routes/_index.tsx": js`
import { useState, useEffect } from "react";
import { Link } from "react-router";
export default function IndexRoute() {
return (
<ul>
<li>
<Link to="/splittable">/splittable</Link>
</li>
<li>
<Link to="/unsplittable">/unsplittable</Link>
</li>
<li>
<Link to="/mixed">/mixed</Link>
</li>
</ul>
);
}
`,
"app/routes/splittable/route.tsx": js`
import type { Route } from "./+types/splittable/route";
import { Form } from "react-router";
// Ensure these style imports are still included in the page even though
// they're not used in the main chunk
import clientLoaderStyles from "./clientLoader.module.css";
import clientActionStyles from "./clientAction.module.css";
import hydrateFallbackStyles from "./hydrateFallback.module.css";
// Usage of this exported function forces any consuming code into the main
// chunk. The variable name is globally unique to prevent name mangling,
// e.g. inSplittableMainChunk$1. The use of console.log prevents dead code
// elimination in the build by introducing a side effect
export const inSplittableMainChunk = () => console.log() || true;
export const clientLoader = async () => {
const pollingPromise = (async () => {
while (globalThis.blockClientLoader !== false) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
})();
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error("Client loader wasn't unblocked after 5s")), 5000);
});
await Promise.race([pollingPromise, timeoutPromise]);
return {
message: "clientLoader in main chunk: " + eval("typeof inSplittableMainChunk === 'function'"),
className: clientLoaderStyles.root,
};
};
export const clientAction = () => ({
message: "clientAction in main chunk: " + eval("typeof inSplittableMainChunk === 'function'"),
className: clientActionStyles.root,
});
export const HydrateFallback = (function() {
(globalThis as any).splittableHydrateFallbackDownloaded = true;
return () => <div data-hydrate-fallback className={hydrateFallbackStyles.root}>Loading...</div>;
})();
export default function SplittableRoute({
loaderData,
actionData,
}: Route.ComponentProps) {
inSplittableMainChunk();
return (
<>
<h1>Splittable Route</h1>
<div
data-loader-data
className={loaderData.className}>
loaderData = {JSON.stringify(loaderData.message)}
</div>
{actionData ? (
<div
data-action-data
className={actionData.className}>
actionData = {JSON.stringify(actionData.message)}
</div>
) : null}
<input type="text" />
<Form method="post">
<button>Submit</button>
</Form>
</>
);
}
`,
"app/routes/splittable/clientLoader.module.css": `
.root { padding: 20px; }
`,
"app/routes/splittable/clientAction.module.css": `
.root { padding: 20px; }
`,
"app/routes/splittable/hydrateFallback.module.css": `
.root { padding: 20px; }
`,
"app/routes/unsplittable.tsx": js`
import type { Route } from "./+types/unsplittable";
import { Form } from "react-router";
// Usage of this exported function forces any consuming code into the main
// chunk. The variable name is globally unique to prevent name mangling,
// e.g. inUnsplittableMainChunk$1. The use of console.log prevents dead code
// elimination in the build by introducing a side effect
export const inUnsplittableMainChunk = () => console.log() || true;
export const clientLoader = async () => {
inUnsplittableMainChunk();
const pollingPromise = (async () => {
while (globalThis.blockClientLoader !== false) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
})();
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error("Client loader wasn't unblocked after 5s")), 5000);
});
await Promise.race([pollingPromise, timeoutPromise]);
return "clientLoader in main chunk: " + eval("typeof inUnsplittableMainChunk === 'function'");
};
export const clientAction = () => {
inUnsplittableMainChunk();
return "clientAction in main chunk: " + eval("typeof inUnsplittableMainChunk === 'function'");
}
export const HydrateFallback = (function() {
inUnsplittableMainChunk();
(globalThis as any).unsplittableHydrateFallbackDownloaded = true;
return () => <div data-hydrate-fallback>Loading...</div>;
})();
export default function UnsplittableRoute({
loaderData,
actionData,
}: Route.ComponentProps) {
inUnsplittableMainChunk();
return (
<>
<h1>Unsplittable Route</h1>
<div data-loader-data>loaderData = {JSON.stringify(loaderData)}</div>
{actionData ? (
<div data-action-data>actionData = {JSON.stringify(actionData)}</div>
) : null}
<input type="text" />
<Form method="post">
<button>Submit</button>
</Form>
</>
);
}
`,
"app/routes/mixed.tsx": js`
import type { Route } from "./+types/mixed";
import { Form } from "react-router";
// Usage of this exported function forces any consuming code into the main
// chunk. The variable name is globally unique to prevent name mangling,
// e.g. inMixedMainChunk$1. The use of console.log prevents dead code
// elimination in the build by introducing a side effect
export const inMixedMainChunk = () => console.log() || true;
export const clientLoader = async () => {
inMixedMainChunk();
const pollingPromise = (async () => {
while (globalThis.blockClientLoader !== false) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
})();
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error("Client loader wasn't unblocked after 2s")), 2000);
});
await Promise.race([pollingPromise, timeoutPromise]);
return "clientLoader in main chunk: " + eval("typeof inMixedMainChunk === 'function'");
};
export const clientAction = () => {
return "clientAction in main chunk: " + eval("typeof inMixedMainChunk === 'function'");
};
export const HydrateFallback = (function() {
inMixedMainChunk();
(globalThis as any).mixedHydrateFallbackDownloaded = true;
return () => <div data-hydrate-fallback>Loading...</div>;
})();
export default function MixedRoute({
loaderData,
actionData,
}: Route.ComponentProps) {
inMixedMainChunk();
return (
<>
<h1>Mixed Route</h1>
<div data-loader-data>loaderData = {JSON.stringify(loaderData)}</div>
{actionData ? (
<div data-action-data>actionData = {JSON.stringify(actionData)}</div>
) : null}
<input type="text" />
<Form method="post">
<button>Submit</button>
</Form>
</>
);
}
`,
};
async function splittableHydrateFallbackDownloaded(page: Page) {
return await page.evaluate(() =>
Boolean((globalThis as any).splittableHydrateFallbackDownloaded)
);
}
async function unsplittableHydrateFallbackDownloaded(page: Page) {
return await page.evaluate(() =>
Boolean((globalThis as any).unsplittableHydrateFallbackDownloaded)
);
}
async function mixedHydrateFallbackDownloaded(page: Page) {
return await page.evaluate(() =>
Boolean((globalThis as any).mixedHydrateFallbackDownloaded)
);
}
async function unblockClientLoader(page: Page) {
await page.evaluate(() => {
(globalThis as any).blockClientLoader = false;
});
}
test.describe("Split route modules", async () => {
test.describe("enabled", () => {
let splitRouteModules = true;
let port: number;
let cwd: string;
let stop: Awaited<ReturnType<typeof reactRouterServe>>;
test.beforeAll(async () => {
port = await getPort();
cwd = await createProject({
"react-router.config.ts": reactRouterConfig({ splitRouteModules }),
"vite.config.js": await viteConfig.basic({ port }),
...files,
});
build({ cwd });
stop = await reactRouterServe({ cwd, port });
});
test.afterAll(() => {
stop();
});
test("supports splitting route modules", async ({ page }) => {
let pageErrors: Error[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${port}`, { waitUntil: "networkidle" });
await unblockClientLoader(page);
expect(pageErrors).toEqual([]);
// Ensure splittable exports are not in main chunk
await page.getByRole("link", { name: "/splittable" }).click();
await expect(page.getByText("Splittable Route")).toBeVisible();
expect(await splittableHydrateFallbackDownloaded(page)).toBe(false);
await expect(page.locator("[data-loader-data]")).toHaveText(
`loaderData = "clientLoader in main chunk: false"`
);
expect(await splittableHydrateFallbackDownloaded(page)).toBe(false);
expect(page.locator("[data-loader-data]")).toHaveCSS("padding", "20px");
await page.getByRole("button").click();
await expect(page.locator("[data-action-data]")).toHaveText(
'actionData = "clientAction in main chunk: false"'
);
expect(page.locator("[data-action-data]")).toHaveCSS("padding", "20px");
await page.goBack();
// Ensure unsplittable exports are in main chunk
await page.getByRole("link", { name: "/unsplittable" }).click();
await expect(page.getByText("Unsplittable Route")).toBeVisible();
expect(await unsplittableHydrateFallbackDownloaded(page)).toBe(true);
await expect(page.locator("[data-loader-data]")).toHaveText(
'loaderData = "clientLoader in main chunk: true"'
);
await page.getByRole("button").click();
await expect(page.locator("[data-action-data]")).toHaveText(
'actionData = "clientAction in main chunk: true"'
);
await page.goBack();
// Ensure mix of splittable and unsplittable exports are handled correctly.
// Note that only the client action is in its own chunk.
await page.getByRole("link", { name: "/mixed" }).click();
await expect(page.getByText("Mixed Route")).toBeVisible();
await expect(page.locator("[data-loader-data]")).toHaveText(
'loaderData = "clientLoader in main chunk: true"'
);
expect(await mixedHydrateFallbackDownloaded(page)).toBe(true);
await page.getByRole("button").click();
await expect(page.locator("[data-action-data]")).toHaveText(
'actionData = "clientAction in main chunk: false"'
);
// Ensure splittable HydrateFallback and client loader work during SSR
await page.goto(`http://localhost:${port}/splittable`);
await expect(page.locator("[data-hydrate-fallback]")).toHaveText(
"Loading..."
);
await expect(page.locator("[data-hydrate-fallback]")).toHaveCSS(
"padding",
"20px"
);
expect(await splittableHydrateFallbackDownloaded(page)).toBe(true);
await unblockClientLoader(page);
await expect(page.locator("[data-loader-data]")).toHaveText(
`loaderData = "clientLoader in main chunk: false"`
);
await expect(page.locator("[data-loader-data]")).toHaveCSS(
"padding",
"20px"
);
// Ensure unsplittable HydrateFallback and client loader work during SSR
await page.goto(`http://localhost:${port}/unsplittable`);
await expect(page.locator("[data-hydrate-fallback]")).toHaveText(
"Loading..."
);
expect(await unsplittableHydrateFallbackDownloaded(page)).toBe(true);
await unblockClientLoader(page);
await expect(page.locator("[data-loader-data]")).toHaveText(
`loaderData = "clientLoader in main chunk: true"`
);
});
});
test.describe("disabled", () => {
let splitRouteModules = false;
let port: number;
let cwd: string;
let stop: Awaited<ReturnType<typeof reactRouterServe>>;
test.beforeAll(async () => {
port = await getPort();
cwd = await createProject({
"react-router.config.ts": reactRouterConfig({ splitRouteModules }),
"vite.config.js": await viteConfig.basic({ port }),
...files,
});
build({ cwd });
stop = await reactRouterServe({ cwd, port });
});
test.afterAll(() => {
stop();
});
test("keeps route module in a single chunk", async ({ page }) => {
let pageErrors: Error[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${port}`, { waitUntil: "networkidle" });
await unblockClientLoader(page);
expect(pageErrors).toEqual([]);
// Ensure splittable exports are kept in main chunk
await page.getByRole("link", { name: "/splittable" }).click();
await expect(page.getByText("Splittable Route")).toBeVisible();
expect(await splittableHydrateFallbackDownloaded(page)).toBe(true);
await expect(page.locator("[data-loader-data]")).toHaveText(
`loaderData = "clientLoader in main chunk: true"`
);
await expect(page.locator("[data-loader-data]")).toHaveCSS(
"padding",
"20px"
);
await page.getByRole("button").click();
await expect(page.locator("[data-action-data]")).toHaveText(
'actionData = "clientAction in main chunk: true"'
);
await expect(page.locator("[data-action-data]")).toHaveCSS(
"padding",
"20px"
);
await page.goBack();
// Ensure unsplittable exports are kept in main chunk
await page.getByRole("link", { name: "/unsplittable" }).click();
await expect(page.getByText("Unsplittable Route")).toBeVisible();
expect(await unsplittableHydrateFallbackDownloaded(page)).toBe(true);
await expect(page.locator("[data-loader-data]")).toHaveText(
'loaderData = "clientLoader in main chunk: true"'
);
await page.getByRole("button").click();
await expect(page.locator("[data-action-data]")).toHaveText(
'actionData = "clientAction in main chunk: true"'
);
// Ensure splittable client loader works during SSR
await page.goto(`http://localhost:${port}/splittable`);
await expect(page.locator("[data-hydrate-fallback]")).toHaveText(
"Loading..."
);
await expect(page.locator("[data-hydrate-fallback]")).toHaveCSS(
"padding",
"20px"
);
await unblockClientLoader(page);
await expect(page.locator("[data-loader-data]")).toHaveText(
`loaderData = "clientLoader in main chunk: true"`
);
// Ensure unsplittable client loader works during SSR
await page.goto(`http://localhost:${port}/unsplittable`);
await expect(page.locator("[data-hydrate-fallback]")).toHaveText(
"Loading..."
);
await unblockClientLoader(page);
await expect(page.locator("[data-loader-data]")).toHaveText(
`loaderData = "clientLoader in main chunk: true"`
);
});
});
test.describe("enforce", () => {
let splitRouteModules = "enforce" as const;
let port: number;
let cwd: string;
test.describe("splittable routes", () => {
test.beforeAll(async () => {
port = await getPort();
cwd = await createProject({
"react-router.config.ts": reactRouterConfig({ splitRouteModules }),
"vite.config.js": await viteConfig.basic({ port }),
// Make unsplittable routes valid so the build can pass
"app/routes/unsplittable.tsx": "export default function(){}",
"app/routes/mixed.tsx": "export default function(){}",
});
});
test("build passes", async () => {
let { status } = build({ cwd });
expect(status).toBe(0);
});
});
test.describe("splittable routes with splittable root route exports", () => {
test.beforeAll(async () => {
port = await getPort();
cwd = await createProject({
"react-router.config.ts": reactRouterConfig({ splitRouteModules }),
"vite.config.js": await viteConfig.basic({ port }),
"app/root.tsx": js`
import { Outlet } from "react-router";
export const clientLoader = () => null;
export const clientAction = () => null;
export default function() {
return <Outlet />;
}
`,
// Make unsplittable routes valid so the build can pass
"app/routes/unsplittable.tsx": "export default function(){}",
"app/routes/mixed.tsx": "export default function(){}",
});
});
test("build passes", async () => {
let { status } = build({ cwd });
expect(status).toBe(0);
});
});
test.describe("splittable routes with unsplittable root route exports", () => {
test.beforeAll(async () => {
port = await getPort();
cwd = await createProject({
"react-router.config.ts": reactRouterConfig({ splitRouteModules }),
"vite.config.js": await viteConfig.basic({ port }),
"app/root.tsx": js`
import { Outlet } from "react-router";
const shared = null;
export const clientLoader = () => shared;
export const clientAction = () => shared;
export default function() {
return <Outlet />;
}
`,
// Make unsplittable routes valid so the build can pass
"app/routes/unsplittable.tsx": "export default function(){}",
"app/routes/mixed.tsx": "export default function(){}",
});
});
test("build passes", async () => {
let { status } = build({ cwd });
expect(status).toBe(0);
});
});
test.describe("unsplittable routes", () => {
test.beforeAll(async () => {
port = await getPort();
cwd = await createProject({
"react-router.config.ts": reactRouterConfig({ splitRouteModules }),
"vite.config.js": await viteConfig.basic({ port }),
...files,
// Ensure we're only testing the mixed route
"app/routes/unsplittable.tsx": "export default function(){}",
});
});
test("build fails", async () => {
let { stderr, status } = build({ cwd });
expect(status).toBe(1);
expect(stderr.toString()).toMatch(
dedent`
Error splitting route module: routes/mixed.tsx
- clientLoader
- HydrateFallback
These exports could not be split into their own chunks because they share code with other exports. You should extract any shared code into its own module and then import it within the route module.
`
);
});
});
});
});