문제: build id는 부트 실패 화면이 보여 주므로 render-boot-failure 청크에 들어간다. react-dom과 scheduler(약 56 KB gzip)가 같은 청크에 있어서 build id만 다른 두 빌드에서 boot·index·render-boot-failure 세 파일의 이름이 바뀌었다. 합계 99,785 B로 초기 JS의 49.4%다. 해시 자산은 1년 immutable로 캐시되는데, 재방문 사용자는 코드가 같아도 release마다 이만큼 다시 받았다. 1101 O1이 같은 것을 재고 채택을 권했지만 결정 기록이 없었다. 고른 방법: codeSplitting.groups에 react-dom·scheduler 그룹을 더한다 (includeDependenciesRecursively: false라 라이브러리 모듈만 묶는다). 같은 비교에서 바뀐 초기 JS가 44,297 B(22.0%)로 준다. 초기 JS는 201,857 → 201,552 B, 초기 파일 수는 25개 그대로다(react-dom 진입 모듈 1.3 KB 청크가 합쳐졌다). 버린 대안: build id를 JS에 넣지 않고 release-manifest.json에서만 읽기. boot까지 바뀌지 않아 더 줄지만, 부트 실패 화면이 build id를 보여 주는 계약을 바꿔야 한다. 위험·한계: boot(39 KB)는 build id로 설정을 대조하므로 계속 바뀐다. 그룹 정규식은 pnpm의 node_modules 배치를 가정한다. 배치가 바뀌어 그룹이 비면 새 테스트가 실패한다. 검증: tests/unit/build-environment-bundle.test.ts가 build id만 다른 두 빌드에서 react-dom이 든 청크의 이름이 같고 그 청크가 render-boot-failure가 아님을 본다(고치기 전 실패). 부트 실패 화면 e2e(tests/e2e/boot-module-failure.spec.ts, chromium) 통과. feature-shape-growth·design-system-initial-chunk·bundle-classification 통과. 두 빌드 비교는 docs/operations/performance-evidence.md에 기록했다. Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-06
224 lines
9.5 KiB
TypeScript
224 lines
9.5 KiB
TypeScript
import path from "node:path";
|
|
|
|
import { defineConfig, loadEnv } from "vite";
|
|
import react from "@vitejs/plugin-react";
|
|
import tailwindcss from "@tailwindcss/vite";
|
|
|
|
import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts";
|
|
import { ENV_REGISTRY } from "./src/contracts/env.ts";
|
|
|
|
/**
|
|
* 13-06. Every VITE_* value Vite loads (shell or `.env*`) is public once
|
|
* something bundles it, so a value the build does not declare is refused
|
|
* rather than carried along.
|
|
*/
|
|
function assertDeclaredBuildVariables(mode: string): void {
|
|
const undeclared = Object.keys(loadEnv(mode, process.cwd(), "VITE_"))
|
|
.filter((name) => !Object.hasOwn(ENV_REGISTRY, name))
|
|
.sort();
|
|
if (undeclared.length > 0) {
|
|
throw new Error(
|
|
`Undeclared VITE_* build variables: ${undeclared.join(", ")}. ` +
|
|
"Declare them in ENV_REGISTRY (src/contracts/env.ts) or unset them; " +
|
|
"VITE_ values are published to the browser.",
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* §6.1. One sub-path, declared once.
|
|
*
|
|
* `VITE_ROUTER_BASE_PATH` already drives the router and the Service Worker
|
|
* scope. Vite's asset `base` was left at its default, so a build served from
|
|
* `/app/` emitted root-absolute asset URLs and loaded nothing: the three
|
|
* consumers of the same setting disagreed. They are read from one value here so
|
|
* a sub-path deployment is coherent or fails at build time.
|
|
*/
|
|
function routerBasePath(environment: NodeJS.ProcessEnv): string {
|
|
const declared = environment["VITE_ROUTER_BASE_PATH"];
|
|
if (declared === undefined || declared === "") return "/";
|
|
if (!declared.startsWith("/") || !declared.endsWith("/")) {
|
|
throw new Error(
|
|
`VITE_ROUTER_BASE_PATH must start and end with "/"; received ${declared}`,
|
|
);
|
|
}
|
|
return declared;
|
|
}
|
|
|
|
/**
|
|
* 13-07. The runtime document ships inside dist, which is served under the
|
|
* base path. An explicit root-relative URL outside it would 404 at boot.
|
|
*/
|
|
function assertRuntimeConfigUnderBase(
|
|
environment: NodeJS.ProcessEnv,
|
|
base: string,
|
|
): void {
|
|
const declared = environment["VITE_RUNTIME_CONFIG_URL"];
|
|
if (declared?.startsWith("/") && !declared.startsWith(base)) {
|
|
throw new Error(
|
|
`VITE_RUNTIME_CONFIG_URL ${declared} is outside VITE_ROUTER_BASE_PATH ${base}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
type ModuleGraph = Readonly<{
|
|
getModuleInfo(id: string): Readonly<{
|
|
importedIds: readonly string[];
|
|
dynamicallyImportedIds: readonly string[];
|
|
}> | null;
|
|
}>;
|
|
|
|
function staticClosure(
|
|
graph: ModuleGraph,
|
|
roots: readonly string[],
|
|
within: (id: string) => boolean = () => true,
|
|
): Set<string> {
|
|
const reached = new Set<string>();
|
|
const pending = [...roots];
|
|
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
|
|
if (reached.has(next) || !within(next)) continue;
|
|
reached.add(next);
|
|
pending.push(...(graph.getModuleInfo(next)?.importedIds ?? []));
|
|
}
|
|
return reached;
|
|
}
|
|
|
|
/**
|
|
* 15-01. Two chunk groups that keep moving the feature runtime halves out of
|
|
* the initial JavaScript from costing more than it saves.
|
|
*
|
|
* - `feature-declarations`: every installed feature's declaration, the static
|
|
* graph under src/features/ that the generated feature index reaches
|
|
* (feature-module.ts, its route contract and messages). A declaration is
|
|
* shared by the boot graph and its own feature's lazy runtime and pages,
|
|
* and rolldown otherwise gives each such set of importers a chunk of its
|
|
* own: one more initial file per feature, which doubled what a feature
|
|
* added to the initial JavaScript.
|
|
* - `feature-platform`: the boot modules the runtime halves also import (HTTP
|
|
* executor, contract runtime, zod). Left to rolldown they split into one
|
|
* initial chunk per set of importers; the per-file gzip overhead and the
|
|
* compression lost across files cost more than the runtime code removed.
|
|
* Modules that the boot-failure screen needs are left out, so
|
|
* render-boot-failure.tsx never depends on this chunk: it must still render
|
|
* when a module of the application graph throws while evaluating (09-03).
|
|
*
|
|
* Both only regroup modules the boot already loads; nothing lazy becomes
|
|
* initial. If feature-declarations comes out empty, the per-feature bound in
|
|
* tests/unit/feature-shape-growth.test.ts fails. feature-platform only moves
|
|
* the platform total (about 2 KB at 15-01), which the bundle budget
|
|
* (FE-GATE-012) checks.
|
|
*/
|
|
function createFeatureChunkGroups(root: string) {
|
|
const at = (file: string) => path.join(root, file);
|
|
const featuresRoot = `${at("src/features")}${path.sep}`;
|
|
let groups: ReadonlyMap<string, string> | undefined;
|
|
const classify = (graph: ModuleGraph): ReadonlyMap<string, string> => {
|
|
const index = graph.getModuleInfo(at("src/.generated/product-feature-index.ts"));
|
|
const declarations = staticClosure(graph, index?.importedIds ?? [], (id) =>
|
|
id.startsWith(featuresRoot),
|
|
);
|
|
const runtimes = staticClosure(
|
|
graph,
|
|
[...declarations].flatMap((id) => graph.getModuleInfo(id)?.dynamicallyImportedIds ?? []),
|
|
);
|
|
const boot = staticClosure(graph, [at("src/bootstrap/boot.tsx")]);
|
|
const bootFailure = staticClosure(graph, [at("src/bootstrap/render-boot-failure.tsx")]);
|
|
const result = new Map<string, string>();
|
|
for (const id of declarations) result.set(id, "feature-declarations");
|
|
for (const id of runtimes) {
|
|
if (boot.has(id) && !bootFailure.has(id) && !declarations.has(id)) {
|
|
result.set(id, "feature-platform");
|
|
}
|
|
}
|
|
return result;
|
|
};
|
|
return (id: string, graph: ModuleGraph): string | null => {
|
|
groups ??= classify(graph);
|
|
return groups.get(id) ?? null;
|
|
};
|
|
}
|
|
|
|
export default defineConfig(({ mode }) => {
|
|
assertDeclaredBuildVariables(mode);
|
|
const base = routerBasePath(process.env);
|
|
assertRuntimeConfigUnderBase(process.env, base);
|
|
return {
|
|
base,
|
|
plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()],
|
|
build: {
|
|
manifest: true,
|
|
sourcemap: false,
|
|
rollupOptions: {
|
|
/**
|
|
* 1101/08-08. The design-system modules have no top-level effects:
|
|
* they declare components, icons and token lists. Declared so, a
|
|
* primitive file none of whose exports a chunk uses is dropped from
|
|
* it, instead of riding the initial chunk because the app shell
|
|
* imports the index that re-exports it. The bundler drops an import
|
|
* kept only for its effect along with its module, so these files hold
|
|
* no such import; tests/unit/design-system-initial-chunk.test.ts
|
|
* checks both. Stylesheets load from bootstrap/main.tsx.
|
|
*
|
|
* Trade: at 08-08 the initial JavaScript fell by 2,718 gzip bytes
|
|
* and the initial chunks rose from 16 to 25. The entry preloads them
|
|
* in parallel, so over HTTP/2 they add no round trip. Over HTTP/1.1
|
|
* they queue for six connections; 1101/14.4 measured that cost and
|
|
* why the chunks stay split ("초기 청크 수와 HTTP/1.1" in
|
|
* docs/operations/performance-evidence.md).
|
|
*/
|
|
treeshake: {
|
|
moduleSideEffects: [
|
|
{
|
|
test: /[\\/]src[\\/]presentation[\\/]design-system[\\/].+\.tsx?$/,
|
|
sideEffects: false,
|
|
},
|
|
],
|
|
},
|
|
output: {
|
|
codeSplitting: {
|
|
groups: [
|
|
// 09-03. The entry now imports the app dynamically, so Vite's
|
|
// preload helper would land in the entry chunk and every lazy
|
|
// chunk would import the entry, whose hash changes with each
|
|
// build id.
|
|
{ name: "preload-helper", test: /vite[\\/]preload-helper/ },
|
|
// 1103/15-06. react-dom and scheduler (about 56 KB gzip) shared
|
|
// the boot-failure chunk with the build id, so a release that
|
|
// only changed the build id renamed half of the initial
|
|
// JavaScript (99,785 of 201,857 B) and returning visitors
|
|
// downloaded it again. In a chunk of their own they keep their
|
|
// name: the same change renames 44,297 B (boot, entry and the
|
|
// boot-failure screen, which hold or import the build id).
|
|
// The boot-failure screen still needs no module of the
|
|
// application graph (09-03): this chunk is a library leaf.
|
|
{
|
|
name: "react-dom",
|
|
test: /[\\/]node_modules[\\/](?:\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/])?(?:react-dom|scheduler)[\\/]/,
|
|
includeDependenciesRecursively: false,
|
|
},
|
|
// 1101/07-03. Every feature's schemas and runtime half import
|
|
// the shared zod adapter. Alone it becomes a chunk of its own
|
|
// once two features share it, and every route and runtime
|
|
// import then preloads one more file (about 50 gzip bytes of
|
|
// initial JavaScript for the second feature). Those imports
|
|
// already preload schema-registry.ts, so the adapter rides
|
|
// that lazy chunk. Both modules stay off the boot graph.
|
|
{
|
|
name: "schema-registry",
|
|
test: /[\\/]src[\\/]contracts[\\/](?:schema-registry|zod-validator)\.ts$/,
|
|
includeDependenciesRecursively: false,
|
|
},
|
|
{
|
|
name: createFeatureChunkGroups(process.cwd()),
|
|
// The boot-failure screen's modules stay out of
|
|
// feature-platform even when a grouped module imports them.
|
|
includeDependenciesRecursively: false,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
};
|
|
});
|