Files
clean-architecture-frontend…/tests/unit/build-environment-bundle.test.ts
DongHyeonka 9f9e459c4d perf(build): 운영 빌드가 react-router의 운영 빌드를 싣는다
문제: react-router 7.18.1의 exports는 모든 조건에서
dist/development/*를 가리킨다. 그 파일은 ENABLE_DEV_WARNINGS = true라
운영 번들의 초기 청크에 라우터 개발 경고 문구("You rendered descendant
…")가 들어 있었다. 운영 콘솔에 개발 경고가 뜨고, 초기 JS가 약 600 B 크다.

고른 방법: vite build일 때만 react-router-dom이 import하는 두 진입점
(react-router, react-router/dom)을 같은 패키지의 dist/production 파일로
alias한다. 경로는 react-router-dom에서 react-router를 resolve한 개발
진입점 옆에서 찾고, 파일이 없으면 빌드를 멈춘다. 개발 서버와 테스트는
개발 빌드를 그대로 써서 경고를 받는다.
버린 대안: 고정 경로 alias(리뷰 실험). 업그레이드로 배치가 바뀌면
조용히 깨진다. react-router에 production 조건을 요청하기는 시점을 정할
수 없어 이 alias를 지울 조건으로만 적었다.

위험·한계: exports 밖 경로를 쓴다. 업그레이드 때 배치가 바뀌면 빌드가
실패한다(조용히 개발 빌드로 돌아가지 않는다). Firefox·WebKit e2e는
돌리지 않았다.

검증: tests/unit/build-environment-bundle.test.ts가 빌드한 JS에 개발
경고 문구가 없음을 본다(고치기 전 chunk-KS7C4IRE 1개에서 실패).
같은 빌드(local-build) 초기 JS 201,552 → 200,939 B(−613 B), 파일 25개.
라우터를 쓰는 e2e 5개 spec 14건(app-shell, reference-route,
reference-save, scroll-restoration, platform-overview, chromium) 통과.

Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-07
2026-11-04 20:25:48 +09:00

111 lines
4.7 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));
// 1103/15-07. react-router's exports map resolves every condition to its
// development build; a production build must carry the production one,
// without the router's development warnings.
const developmentWarnings = first.contents
.filter(({ file, text }) => file.endsWith(".js") && text.includes("You rendered descendant"))
.map(({ file }) => path.basename(file));
expect(developmentWarnings).toEqual([]);
}, 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);
});