Files
clean-architecture-frontend…/tests/unit/build-environment-bundle.test.ts
T
DongHyeonka af6d0a9f01 perf(build): react-dom을 자기 청크로 빼 build id만 바뀐 release의 캐시 손실을 줄인다
문제: 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
2026-11-04 20:23:54 +09:00

103 lines
4.2 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { filesBelow } from "../../scripts/lib/removal-fixture.ts";
/**
* 13-06. Which VITE_* values reach the bundle. The declared values the app
* reads must still be there (build id, commit, runtime config URL, base path);
* a declared value nothing reads and an undeclared one must not be, and the
* design-system chunk must not change with the build id.
*/
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
function inheritedEnvironment(): NodeJS.ProcessEnv {
return Object.fromEntries(
Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")),
);
}
async function build(variables: Readonly<Record<string, string>>) {
const outDir = await mkdtemp(path.join(tmpdir(), "build-environment-"));
roots.push(outDir);
const run = spawnSync(
path.resolve("node_modules/.bin/vite"),
["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"],
{ encoding: "utf8", env: { ...inheritedEnvironment(), ...variables } },
);
const contents = run.status === 0
? await Promise.all(
(await filesBelow(outDir))
.filter((file) => /\.(?:js|html)$/u.test(file))
.map(async (file) => ({ file, text: await readFile(file, "utf8") })),
)
: [];
return { run, outDir, contents };
}
const DECLARED = Object.freeze({
VITE_COMMIT_SHA: "commit-probe-13",
VITE_ROUTER_BASE_PATH: "/base-probe/",
VITE_RUNTIME_CONFIG_URL: "/base-probe/runtime-probe.json",
// Declared, but applied by the index generator; the bundle never reads it.
VITE_PRODUCT_FEATURES: "unreferenced-probe-13",
});
describe("build variables in the bundle (13-06)", () => {
it("keeps the values the app reads and nothing else", async () => {
const first = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-1" });
expect(first.run.stderr).toBe("");
expect(first.run.status).toBe(0);
const bundled = (value: string) =>
first.contents.some(({ text }) => text.includes(value));
expect(bundled("build-probe-1")).toBe(true);
expect(bundled("commit-probe-13")).toBe(true);
expect(bundled("/base-probe/runtime-probe.json")).toBe(true);
const html = first.contents.find(({ file }) => file.endsWith("index.html"));
expect(html?.text).toContain('src="/base-probe/assets/');
expect(bundled("unreferenced-probe-13")).toBe(false);
const second = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-2" });
expect(second.run.status).toBe(0);
// 1101/08-08 split the design system over chunks named after its
// primitives; the one with the button primitive stands for them.
const designSystem = ({ contents }: Awaited<ReturnType<typeof build>>) =>
contents
.filter(({ file, text }) =>
file.endsWith(".js") && text.includes("ui-button--pending"),
)
.map(({ file }) => path.basename(file));
const firstChunks = designSystem(first);
expect(firstChunks).toHaveLength(1);
expect(designSystem(second)).toEqual(firstChunks);
// 1103/15-06. react-dom is about 56 KB of the initial JavaScript. It sat
// in the boot-failure chunk with the build id, so every release renamed
// it and returning visitors downloaded it again. Its own chunk keeps the
// name while only the build id changes.
const reactDom = ({ contents }: Awaited<ReturnType<typeof build>>) =>
contents
.filter(({ file, text }) => file.endsWith(".js") && text.includes("__reactContainer$"))
.map(({ file }) => path.basename(file));
expect(reactDom(first)).toHaveLength(1);
expect(reactDom(first)[0]).not.toMatch(/render-boot-failure/u);
expect(reactDom(second)).toEqual(reactDom(first));
}, 120_000);
it("refuses a VITE_* variable the build does not declare", async () => {
const refused = await build({ VITE_PAYMENT_KEY: "sk_live_probe" });
expect(refused.run.status).not.toBe(0);
expect(refused.run.stderr + refused.run.stdout).toMatch(
/Undeclared VITE_\* build variables: VITE_PAYMENT_KEY/u,
);
}, 120_000);
});