Skip to content
TypeScript

perf(web): pre-bundle startup chunks when a shared dev server starts (#22210)

Theo Browne72bdf1e658c6
diff --git a/apps/web/src/bundledDev.test.ts b/apps/web/src/bundledDev.test.ts
index 0b11c52a5e3..aaba58c8a7e 100644
--- a/apps/web/src/bundledDev.test.ts
+++ b/apps/web/src/bundledDev.test.ts
@@ -12,6 +12,7 @@ import { createLogger, createServer } from "vite-plus";
import { expect, it } from "vite-plus/test";
import { tailwindPlugins } from "../vite/tailwind";
+import { warmLazyEntries } from "../vite/warmBundledDev";
const execFile = NodeUtil.promisify(NodeChildProcess.execFile);
@@ -222,3 +223,42 @@ it("hot updates Tailwind classes when a source file changes in bundled dev", asy
await NodeFSP.rm(root, { recursive: true, force: true });
}
});
+
+it("warms the wanted lazy chunk chain and nothing else", async () => {
+ const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-warm-"));
+ let server: Awaited<ReturnType<typeof createServer>> | undefined;
+
+ try {
+ await NodeFSP.mkdir(NodePath.join(root, "src"));
+ await NodeFSP.writeFile(
+ NodePath.join(root, "index.html"),
+ '<html><body><script type="module" src="/src/bootstrap.ts"></script></body></html>',
+ );
+ await NodeFSP.writeFile(NodePath.join(root, "src/bootstrap.ts"), 'void import("./main");');
+ await NodeFSP.writeFile(
+ NodePath.join(root, "src/main.ts"),
+ 'export const route = () => import("./route"); export const rare = () => import("./rare");',
+ );
+ await NodeFSP.writeFile(NodePath.join(root, "src/route.ts"), "export const route = 1;");
+ await NodeFSP.writeFile(NodePath.join(root, "src/rare.ts"), "export const rare = 1;");
+
+ server = await createServer({
+ configFile: false,
+ root,
+ logLevel: "silent",
+ experimental: { bundledDev: true },
+ server: { host: "127.0.0.1", port: 0 },
+ });
+ await server.listen();
+
+ // The route is only discoverable after main compiles, so this also covers the pass walk.
+ const warmed = await warmLazyEntries(server, ["src/main.ts", "src/route.ts"]);
+ expect(warmed.map((id) => NodePath.relative(root, id.split("?")[0] ?? id))).toEqual([
+ "src/main.ts",
+ "src/route.ts",
+ ]);
+ } finally {
+ await server?.close();
+ await NodeFSP.rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index cd50954cd76..6e550f68146 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -18,6 +18,7 @@ import {
import { loadRepoEnv } from "../../scripts/lib/public-config";
import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses";
import { tailwindPlugins } from "./vite/tailwind";
+import { warmBundledDevPlugin } from "./vite/warmBundledDev";
const repoEnv = loadRepoEnv();
Object.assign(process.env, repoEnv);
@@ -186,6 +187,7 @@ export default defineConfig(() => {
tanstackRouter({ autoCodeSplitting: true }),
react({ compiler: true }),
tailwindPlugins(bundledDev),
+ warmBundledDevPlugin(),
],
optimizeDeps: {
include: [
@@ -239,7 +241,8 @@ export default defineConfig(() => {
// Transform the whole module graph at server start instead of on the
// first request. Without this, a cold worktree discovers and transforms
// modules one import-level at a time while the browser waits — which
- // over a tailnet origin turns into minutes of waterfall.
+ // over a tailnet origin turns into minutes of waterfall. Bundled dev
+ // ignores this; warmBundledDevPlugin covers it there.
warmup: {
clientFiles: ["./src/main.tsx"],
},
diff --git a/apps/web/vite/warmBundledDev.ts b/apps/web/vite/warmBundledDev.ts
new file mode 100644
index 00000000000..41c95feb45c
--- /dev/null
+++ b/apps/web/vite/warmBundledDev.ts
@@ -0,0 +1,125 @@
+import type { Plugin, ViteDevServer } from "vite-plus";
+
+// What the first page load pulls in: the app, the managed-auth shell, the chat
+// layout and its landing routes, and the sidebar's project icons.
+const STARTUP_LAZY_ENTRIES = [
+ "src/main.tsx",
+ "src/components/clerk/BrowserManagedAuthShell.tsx",
+ "src/routes/_chat.tsx",
+ "src/routes/_chat.index.tsx",
+ "src/routes/_chat.$environmentId.$threadId.tsx",
+ "src/lib/lucideIconByName.ts",
+];
+
+const WARMUP_CLIENT_ID = "t3code-startup-warmup";
+
+// Bundled dev keeps these private and untyped. A Vite upgrade that moves them
+// skips the warmup or logs a warning, never breaks dev; bundledDev.test.ts
+// fails so the upgrade cannot drop the warmup silently.
+interface BundledDevInternals {
+ waitForInitialBuildFinish(): Promise<void>;
+ triggerLazyBundling(
+ moduleId: string,
+ clientId: string,
+ ): Promise<{ readonly filename: string } | undefined>;
+ markPayloadDelivered(filename: string): void;
+ readonly devEngine: {
+ readonly moduleGraph: {
+ getModuleIds(): readonly string[];
+ getModuleInfo(id: string): { readonly dynamicallyImportedIds: readonly string[] } | null;
+ };
+ removeClient(clientId: string): Promise<void>;
+ };
+}
+
+function hasBundledDevInternals(value: unknown): value is BundledDevInternals {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "waitForInitialBuildFinish" in value &&
+ typeof value.waitForInitialBuildFinish === "function" &&
+ "triggerLazyBundling" in value &&
+ typeof value.triggerLazyBundling === "function" &&
+ "markPayloadDelivered" in value &&
+ typeof value.markPayloadDelivered === "function"
+ );
+}
+
+/**
+ * Compiles `entries` as lazy chunks once, for a throwaway client, and returns
+ * the lazy module ids it compiled. The browser's own requests then reuse
+ * Rolldown's transform cache. Entries are paths relative to the Vite root.
+ */
+export async function warmLazyEntries(
+ server: ViteDevServer,
+ entries: readonly string[],
+): Promise<string[]> {
+ // Widened so the guard narrows to the internals, not to Vite's public class.
+ const bundledDev: unknown = server.environments.client.bundledDev;
+ if (!hasBundledDevInternals(bundledDev)) return [];
+ await bundledDev.waitForInitialBuildFinish();
+
+ const { moduleGraph } = bundledDev.devEngine;
+ // Vite's root and Rolldown's module ids are both absolute, slash-separated paths.
+ const wanted = new Set(entries.map((entry) => `${server.config.root}/${entry}`));
+ const warmed = new Set<string>();
+ // A lazy entry is only in the graph after its parent compiled, so walk in
+ // passes. Each pass compiles at least one new wanted id, so it ends.
+ const nextLazyIds = () =>
+ new Set(
+ moduleGraph
+ .getModuleIds()
+ .flatMap((id) => moduleGraph.getModuleInfo(id)?.dynamicallyImportedIds ?? [])
+ .filter(
+ (id) =>
+ id.includes("rolldown-lazy") && !warmed.has(id) && wanted.has(id.split("?")[0] ?? id),
+ ),
+ );
+
+ try {
+ for (let pending = nextLazyIds(); pending.size > 0; pending = nextLazyIds()) {
+ for (const id of pending) {
+ warmed.add(id);
+ const result = await bundledDev.triggerLazyBundling(id, WARMUP_CLIENT_ID);
+ // Acked so the engine drops the pending payload instead of holding the chunk.
+ if (result) bundledDev.markPayloadDelivered(result.filename);
+ }
+ }
+ } finally {
+ await bundledDev.devEngine.removeClient(WARMUP_CLIENT_ID);
+ }
+ return [...warmed];
+}
+
+// Bundled dev builds only the small bootstrap entry at startup. The app and its
+// routes are lazy chunks, compiled on first request, one import level at a
+// time. Cold, that chain costs ~25s of serial compile before first paint
+// (`server.warmup` does nothing in bundled dev). Warming it as soon as the
+// server listens leaves the browser mostly codegen.
+export function warmBundledDevPlugin(): Plugin {
+ return {
+ name: "t3code:warm-bundled-dev",
+ apply: "serve",
+ configureServer(server) {
+ if (!server.config.experimental.bundledDev) return;
+ server.httpServer?.once("listening", () => {
+ const startedAt = performance.now();
+ warmLazyEntries(server, STARTUP_LAZY_ENTRIES).then(
+ (warmed) => {
+ if (warmed.length === 0) return;
+ const seconds = ((performance.now() - startedAt) / 1000).toFixed(1);
+ server.config.logger.info(
+ `[t3code] pre-bundled ${String(warmed.length)} startup chunks in ${seconds}s`,
+ { timestamp: true },
+ );
+ },
+ (error: unknown) => {
+ server.config.logger.warn(`[t3code] startup chunk warmup failed: ${String(error)}`, {
+ timestamp: true,
+ });
+ },
+ );
+ });
+ },
+ };
+}
diff --git a/docs/operations/development.md b/docs/operations/development.md
index 7346612d965..7e6c799a447 100644
--- a/docs/operations/development.md
+++ b/docs/operations/development.md
@@ -52,9 +52,13 @@ when changing this setup:
chunks. Static imports can work on first load and fail after a route split.
- Bundled dev rebuilds Tailwind through watched files. Its ordinary Vite hot-update hook expects
a server/module graph that Rolldown does not provide.
+- The app and its routes are lazy chunks, built on first request. A plugin pre-bundles the
+ startup chain when the server starts. Renaming or moving a startup route or the app entry
+ silently drops it from that list.
-The workarounds live in the [web entry](../../apps/web/src/bootstrap.ts) and
-[Tailwind plugin](../../apps/web/vite/tailwind.ts).
+The workarounds live in the [web entry](../../apps/web/src/bootstrap.ts),
+[Tailwind plugin](../../apps/web/vite/tailwind.ts), and
+[startup warmup](../../apps/web/vite/warmBundledDev.ts).
#### Reusable dev credential