Files
clean-architecture-frontend…/tests/unit/design-system-initial-chunk.test.ts
T
DongHyeonka 3d34da115a perf(styles): Tailwind가 src 밖 파일의 낱말로 유틸리티를 만들지 않는다
`src/presentation/styles/theme.css`의 `@import "tailwindcss";`에 `source()`가
없어 Tailwind v4가 `.gitignore` 밖 파일을 모두 훑는다. 템플릿 TSX는 유틸리티
class를 쓰지 않고 `@apply`만 쓰는데, 빌드 CSS의 `@layer utilities`에 docs·
tests·scripts의 낱말에서 나온 규칙 35~40개(`.shadow\/canary`, `.sepia`,
`.cursor-not-allowed`, `.\!relative` 등)가 실린다. 모든 페이지가 기다리는 CSS가
약 0.7~0.9 KB gzip 커지고, 문서나 시험만 고친 release도 CSS 이름이 바뀌어
재방문자가 CSS를 다시 받는다.

고른 방법: `@import "tailwindcss" source("../../");`로 훑는 범위를 `src/`로
좁힌다. 제품이 `src/` 안의 className에 유틸리티를 쓰면 그대로 생긴다. 버린
대안: `source(none)`(제품이 유틸리티 class를 쓸 수 없어진다. 디자인 시스템
계약을 바꾸는 일이다).

위험·한계: 유틸리티 class를 `src/` 밖(예: `index.html`)에만 쓴 제품은 그
규칙을 잃는다. 템플릿에는 그런 곳이 없다.

검증: `tests/unit/design-system-initial-chunk.test.ts`의 새 사례가 src 밖
fixture(`tests/fixtures/tailwind-source/outside-src.txt`의
`outline-[3.21px]`)가 빌드 CSS에 없음을 본다. 고치기 전에 실패하고 고친 뒤
통과한다. 시각 골든은 FE-GATE-008이 본다(desktop, PR 본문).

Refs: 1112/06-03
2026-11-13 19:03:18 +09:00

117 lines
4.3 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { classifyViteJavascript } from "../../scripts/lib/classify-vite-bundle.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
/**
* 1101/08-08. A bundler places a module, not an export, in a chunk. A
* primitive only a lazy screen renders must not ride the initial JavaScript
* because it shares a file, or the barrel, with one the app shell renders.
*/
const DESIGN_SYSTEM = "src/presentation/design-system";
// Classes that only the primitives the template's lazy screens use render.
const LAZY_ONLY_CLASSES = Object.freeze([
"ui-alert",
"ui-badge",
"ui-breadcrumbs",
"ui-card",
"ui-data-table",
"ui-menu",
"ui-popover",
"ui-progress",
"ui-radio-group",
"ui-switch",
"ui-tabs",
"ui-toast",
"ui-tooltip",
]);
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
let built: Promise<string> | undefined;
/** One production build for the file's tests. */
function build(): Promise<string> {
built ??= (async () => {
const outDir = await mkdtemp(path.join(tmpdir(), "design-system-chunk-"));
roots.push(outDir);
const environment = Object.fromEntries(
Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")),
);
const run = spawnSync(
path.resolve("node_modules/.bin/vite"),
["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"],
{ encoding: "utf8", env: environment },
);
expect(run.stderr).toBe("");
expect(run.status).toBe(0);
return outDir;
})();
return built;
}
async function initialJavascript(): Promise<string> {
const outDir = await build();
const manifest = JSON.parse(
await readFile(path.join(outDir, ".vite/manifest.json"), "utf8"),
) as Parameters<typeof classifyViteJavascript>[0];
const { initialFiles } = classifyViteJavascript(manifest);
const sources = await Promise.all(
initialFiles.map((file) => readFile(path.join(outDir, file), "utf8")),
);
return sources.join("\n");
}
const renders = (code: string, className: string) =>
new RegExp(`(?<![\\w-])${className}(?![\\w-])`, "u").test(code);
describe("design-system code in the initial JavaScript (1101/08-08)", () => {
it("leaves the primitives only lazy screens use out of the initial chunks", async () => {
const code = await initialJavascript();
// The shell's drawer is initial; without it the check proves nothing.
expect(renders(code, "ui-drawer")).toBe(true);
expect(LAZY_ONLY_CLASSES.filter((name) => renders(code, name))).toEqual([]);
}, childProcessTimeout(4_556));
// 1112/06-03. Tailwind scans the files it is pointed at for class names.
// Words in docs, tests and scripts must not add rules to the stylesheet
// every page blocks on (tests/fixtures/tailwind-source/outside-src.txt).
it("generates utilities from src only, not from docs, tests or scripts", async () => {
const outDir = await build();
const assets = path.join(outDir, "assets");
const stylesheets = (await readdir(assets)).filter((file) => file.endsWith(".css"));
const css = (
await Promise.all(stylesheets.map((file) => readFile(path.join(assets, file), "utf8")))
).join("\n");
expect(css).toContain(".ui-button");
expect(css).not.toContain("3.21px");
}, childProcessTimeout(4_556));
// vite.config.ts declares these modules free of side effects, so the bundler
// drops a module none of whose exports is used. An import kept only for its
// effect (a stylesheet, a polyfill, a registration) would vanish with it.
it("keeps every design-system module free of imports kept for their effect", async () => {
const files = (await readdir(DESIGN_SYSTEM, { recursive: true }))
.filter((file) => /\.tsx?$/u.test(file) && !file.includes(".stories."));
expect(files.length).toBeGreaterThan(0);
const offenders: string[] = [];
for (const file of files) {
const source = await readFile(path.join(DESIGN_SYSTEM, file), "utf8");
if (/^\s*import\s*["']/mu.test(source)) offenders.push(file);
}
expect(offenders).toEqual([]);
});
});