문제
셸은 design-system/index.ts에서 Button·Drawer·Select를 import한다. 번들러는
배럴이 다시 내보내는 모듈을 side effect가 있다고 보고 모두 실행 순서대로
싣는다. 그래서 갤러리와 예제 화면만 쓰는 Tooltip·Menu·Toast·Tabs·Card·
Alert 등이 초기 청크(design-system-*.js)에 있다. 초기 JS는 203,818 B로
예산 204,800 B에서 982 B 남았다. 파일을 나눈 앞 커밋만으로는 바뀌지
않는다.
고른 방법
- vite.config.ts의 treeshake.moduleSideEffects 규칙으로
src/presentation/design-system/ 아래 .ts·.tsx를 side effect 없음으로
선언한다. 이 파일들은 컴포넌트·아이콘·토큰 목록 선언만 한다. CSS
import는 bootstrap/main.tsx 한 곳뿐이고 이 범위 밖이다.
- 결정: 바이트를 줄인다. 예산이 걸린 지표는 바이트이고, 늘어나는 청크는
진입 청크의 preload 목록(__vitePreload)으로 병렬로 받으므로 HTTP/2에서
왕복이 늘지 않는다. 재검토 조건(HTTP/1.1 호스팅이면 청크 수가 비용)을
설정 주석에 적었다.
- 새 테스트 tests/unit/design-system-initial-chunk.test.ts
- 실제 vite build를 돌려 초기 청크에 lazy 화면 전용 클래스 13개가
없는지 본다. 셸의 ui-drawer가 있는지를 같이 봐서 빈 결과로 통과하지
않게 한다.
- design-system 파일에 효과만을 위한 import(import "x")가 없는지 본다.
선언 아래에서는 그런 import가 모듈과 함께 사라지기 때문이다.
- build-environment-bundle 테스트(13-06)는 design-system-* 청크 이름을
찾았다. 그 청크가 없어져서, Button 코드(ui-button--pending)가 든 청크가
build id를 바꿔도 같은지로 바꾼다. 두 build id로 빌드해 보면 바뀌는
파일은 boot·index·render-boot-failure 셋뿐이다.
버린 대안
- 파일 분리만: 실측 효과 없음(203,824 B, 16개).
- manualChunks로 청크 이름을 고정: 제품이 primitive를 쓸 때마다 다시
맞춰야 한다.
- 청크 수 줄이기: 15-01 청크 그룹과 같이 봤다. rolldown의 $initial 태그는
main.tsx가 앱을 동적으로 import해서(09-03) 아무것도 잡지 않았다(25개,
+16 B). 모듈 그래프로 boot 정적 closure를 만들면 배럴을 따라 갤러리
primitive까지 잡혀 다시 초기 청크로 간다. 바이트 손해 없이 줄일 방법을
찾지 못해 늘어난 수를 둔다.
위험·한계
- 초기 청크가 16개에서 25개로 는다(결정 당시 추정 21개보다 많다. 앞
커밋의 파일 분리로 button·field·select가 따로 나온다). 전체(초기+lazy)
gzip은 232,231 → 236,253 B로 4,022 B 는다. 첫 화면만 보는 사용자는
2,718 B 덜 받고, 모든 화면을 도는 사용자는 청크 경계 비용만큼 더 받는다.
- 새 파일에 모듈 최상위 효과(전역 등록 등)를 넣으면 이 선언이 그 효과를
지울 수 있다. 효과만을 위한 import는 테스트가 막지만, 최상위 문장은
막지 않는다. 설정 주석에 적었다.
- lazy 청크 예산(청크당 122,880 B)에는 영향이 없다. 가장 큰 lazy 청크는
8,431 B다.
- 화면 변화 없음: 같은 코드를 다른 청크에서 받는다.
검증
- RED(앞 커밋 상태): 새 테스트가 실패. 초기 청크에 ui-alert·ui-badge·
ui-card·ui-data-table·ui-menu·ui-progress·ui-radio-group·ui-switch·
ui-tabs·ui-toast·ui-tooltip 11개가 있었다.
- GREEN: design-system-initial-chunk·build-environment-bundle·
design-system-contract·product-index-entrypoints·bundle-classification·
sub-path-deployment·product-feature-selection-build 통과.
- 빌드(flock, build-frontend.ts): 초기 JS gzip 203,818 → 201,100 B
(-2,718 B, 예산 여유 982 → 3,700 B), 초기 청크 16 → 25개, lazy 청크
17 → 20개.
- node scripts/run-vitest.ts run tests/component: 35파일 228/228 통과.
- Chromium e2e(vite preview, 위 빌드): ui-gallery·design-system-
interactions·app-shell·accessibility·platform-overview·reference-form·
reference-route·reference-save·theme·typography·responsive·compact-
smoke·i18n·scroll-restoration 55/55 통과.
- tsc(app·node·test), 바꾼 파일 eslint 통과.
Refs: docs/reviews/2026-11-01-maturity-review/08-presentation.md 08-08
197 lines
7.7 KiB
TypeScript
197 lines
7.7 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. Revisit when
|
|
* the app is served over HTTP/1.1, where every chunk costs a
|
|
* connection slot.
|
|
*/
|
|
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/ },
|
|
{
|
|
name: createFeatureChunkGroups(process.cwd()),
|
|
// The boot-failure screen's modules stay out of
|
|
// feature-platform even when a grouped module imports them.
|
|
includeDependenciesRecursively: false,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
};
|
|
});
|