문제
08-08은 초기 JS 바이트를 줄이는 대신 초기 파일을 16개에서 25개(entry
포함 26개)로 늘렸고, "HTTP/1.1 호스팅이면 다시 본다"를 남겼다. vite
preview도 HTTP/1.1이다. 비용을 잰 적이 없어 위험이 열려 있었다.
고른 방법
- 지금 빌드와 묶은 빌드 두 가지를 쟀다. (가) 08-08이 나눈 초기 primitive
청크 4개(field·button·select·page-templates)를 하나로. (나) 묶을 수 있는
초기 청크 14개를 하나로(entry·preload-helper·boot, 부트 실패 화면 closure,
15-01 그룹은 뺐다). 같은 커밋을 임시 복사본에서 그룹 하나만 더해 빌드했다.
- 측정: vite preview(HTTP/1.1, gzip), Chromium CDP 네트워크 에뮬레이션
(DevTools Fast 3G·Fast 4G 값), 새 context·캐시 없음, 첫 화면 =
boot 셸이 사라지고 route h1이 들어온 시각. 세 빌드를 번갈아 7번씩, 중앙값.
HTTP/2(node:http2, 자체 서명 인증서, gzip)도 같은 방법으로 쟀다.
- 결과(Fast 3G / Fast 4G 중앙값)
- 지금 26개 202,782 B: 5,887 / 1,874 ms
- (가) 23개 201,818 B: 5,426 / 1,764 ms
- (나) 13개 198,673 B: 4,930 / 1,535 ms
- HTTP/2: 지금 4,793 / 1,444, (가) 4,769 / 1,440, (나) 4,708 / 1,422 ms
- 판단: 묶지 않는다. 측정값과 판단을 performance-evidence.md에 적고,
vite.config.ts의 "재검토" 주석이 그 절을 가리키게 한다.
- (가)·(나)는 이 빌드의 청크 안 모듈 목록을 그대로 적어 만들었다. 규칙으로
고를 방법이 없었다. boot 정적 closure는 design-system 배럴을 지나 갤러리
전용 primitive까지 잡는다. rolldown `$initial` 태그는 entry가 앱을 dynamic
import로 읽어서(09-03) 아무것도 잡지 않는다. boot.tsx를 entry로 더하면
manifest 분류가 lazy 화면까지 초기로 센다(28개, 216,820 B, 예산 초과).
- 고정 목록은 셸이 쓰는 primitive가 바뀔 때마다 맞춰야 하고, 낡아도
실패하는 검사가 없다. 08-08이 같은 이유로 manualChunks 이름 고정을 버렸다.
- 템플릿은 HTTP/2 이상 서빙을 전제로 본다. HTTP/1.1로만 서빙하는 제품은
(나) 같은 그룹을 넣고 셸을 바꿀 때마다 다시 잰다고 문서에 적었다.
버린 대안
- (나)를 고정 목록으로 넣기: HTTP/1.1에서 Fast 3G 0.96초 빠르지만 숨은
결합이다(위).
- (가)만 넣기: 0.46초. 같은 이유.
위험·한계
- HTTP/1.1로 서빙하는 다운스트림은 첫 화면이 Fast 3G에서 약 1초 늦다.
이 커밋은 그 비용을 없애지 않고 숫자와 전제를 적는다. 호스팅 HTTP 버전을
검사하는 게이트는 없다(FE-GATE-019 probe 밖).
- 측정은 이 머신의 loopback과 CDP 에뮬레이션이다. 연결 수립(TCP·TLS) 비용은
CDP 지연에 들어가지 않는다. loadavg는 HTTP/1.1 측정 6~20, HTTP/2 측정
3~6이라 두 표끼리는 비교하지 않는다. 각 표 안은 번갈아 재서 비교할 수 있다.
검증
- 빌드 바이트: classify-vite-bundle + gzipSync(check:bundle과 같은 계산).
지금 빌드는 기준 202,770 B(local-build)와 맞다.
- 측정 스크립트와 로그는 커밋하지 않았다(worktree의 .tmp/ra/, 일회성).
- node scripts/verify-documentation-readiness.ts: PASS_SCOPED.
- npx eslint vite.config.ts, npx tsc --project tsconfig.node.json --noEmit 통과.
210 lines
8.6 KiB
TypeScript
210 lines
8.6 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/ },
|
|
// 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,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
};
|
|
});
|