[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,92 +2,160 @@
|
||||
id: wiki-2026-0508-code-minification
|
||||
title: Code Minification
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-D932E1]
|
||||
aliases: [Minification, JS Minify, CSS Minify, Bundle Minification]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [build, performance, javascript, web]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Code Minification"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: javascript
|
||||
framework: esbuild/swc/terser
|
||||
---
|
||||
|
||||
# [[Code Minification]]
|
||||
# Code Minification
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 코드 축소(Code Minification)는 브라우저 등으로 코드를 배포할 때 소스 코드의 크기를 최소화하고 전송 및 렌더링 시간을 단축하기 위해 사용되는 소프트웨어 최적화 기법입니다 [1, 2]. 이 기법은 코드의 본래 실행 의미(semantics)를 변경하지 않은 채, 공백, 줄 바꿈, 주석 등 의미가 없는 요소를 제거하고 변수 이름을 짧게 변경하는 등의 표면적 변환을 수행합니다 [1, 2]. 가독성을 높이는 코드 포매팅(Code [[Formatting]])과 달리 코드 축소는 오히려 코드의 가독성을 저하시키며, 주로 소프트웨어 개발 완료 후 배포 직전에 자동화 도구에 의해 실행됩니다 [3].
|
||||
## 매 한 줄
|
||||
> **"매 source code 의 semantic 보존 + size 의 minimize"**. 매 whitespace/comment 제거 + identifier rename + dead code elimination + constant folding. 2026 의 esbuild/SWC/OXC 의 native-speed mainstream, Terser 의 max compression fallback.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **목적과 주요 기법:** 코드 축소의 주요 목적은 소스 코드 형태로 배포되는 소프트웨어의 용량을 줄이는 것이며, 특히 웹 개발 환경에서 페이지 렌더링 속도를 가속화하는 데 흔히 사용됩니다 [2]. 이를 위해 컴파일러나 인터프리터의 실행에 영향을 주지 않는 공백, 줄 바꿈, 주석 등을 제거할 뿐만 아니라, 변수나 클래스 등의 식별자(identifier) 이름을 간결한 대체어로 변경하는 다소 침투적인(invasive) 수정도 포함합니다 [2].
|
||||
* **코드 가독성과 실행 의미 보존:** 축소된 코드는 원본 코드의 실행 의미(semantics)를 완벽하게 중립적으로 보존해야만 성립될 수 있습니다 [1, 2]. 다만, 인간이 읽기 쉽도록 일정한 스타일을 강제하는 코드 포매팅과 정반대로, 축소화 과정은 불필요한 모든 문자를 제거하므로 코드의 가독성을 크게 떨어뜨리는 결과를 낳습니다 [3].
|
||||
* **코드 작성자 인식(Code Stylometry)에 미치는 영향:** 변수명 지정 방식, 공백 사용, 주석 처리 등은 프로그래머 고유의 코딩 스타일을 나타내는 주요 특징입니다. 코드 축소는 이러한 불필요한 문자 및 식별자 이름을 일괄적으로 지우거나 변경하므로 작성자 고유의 흔적을 훼손하게 됩니다 [4]. 관련 연구에 따르면 코드 축소를 적용할 경우 작성자 인식 정확도가 약 17.86% 감소하여, 코드 문체 분석(Code Stylometry)을 통한 작성자 식별을 더 어렵게 만드는 것으로 나타났습니다 [4].
|
||||
* **성능 사례:** Python 코드의 축소를 지원하는 도구인 'Python Minifier'의 실험 사례를 보면, 축소화 작업 후 소스 코드 라인 수(SLOC)는 60%, 문자 수는 37%나 감소하여 매우 큰 파일 크기 최적화 효과를 보여주었습니다 [5, 6].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 변환 단계
|
||||
- **Strip**: whitespace, comments, semicolon redundancy.
|
||||
- **Mangle**: local identifier → 매 short (a, b, c).
|
||||
- **Compress**: constant fold, DCE, inline single-use, sequence expression.
|
||||
- **Property mangle** (optional): `obj.privateField` → `obj.a` (매 risky).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Code Formatting]], Code Stylometry
|
||||
- **Projects/Contexts:** Web Development, Python Minifier
|
||||
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다.
|
||||
### 매 Tree shaking
|
||||
- ES module static imports 의 분석 → 매 unused exports 의 제거.
|
||||
- `sideEffects: false` in package.json 의 강력한 hint.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 Source maps
|
||||
- Mangled output 의 production debugging 의 essential.
|
||||
- `//# sourceMappingURL=app.js.map` + Sentry/DataDog upload.
|
||||
|
||||
---
|
||||
### 매 응용
|
||||
1. JS bundle 의 70-80% 크기 reduction (gzip 후 추가).
|
||||
2. CSS 의 50% reduction (whitespace + selector merging).
|
||||
3. HTML 의 inline asset minification (Astro, Next).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### esbuild (fastest, default for new)
|
||||
```javascript
|
||||
// build.mjs
|
||||
import { build } from 'esbuild';
|
||||
await build({
|
||||
entryPoints: ['src/app.ts'],
|
||||
bundle: true,
|
||||
minify: true, // whitespace + identifier + syntax
|
||||
sourcemap: true,
|
||||
target: ['es2022'],
|
||||
treeShaking: true,
|
||||
outfile: 'dist/app.js',
|
||||
});
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### SWC (Rust, used by Next/Parcel)
|
||||
```javascript
|
||||
// .swcrc
|
||||
{
|
||||
"jsc": { "target": "es2022", "minify": { "compress": true, "mangle": true } },
|
||||
"minify": true,
|
||||
"sourceMaps": true
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Terser (max compression, slower)
|
||||
```javascript
|
||||
import { minify } from 'terser';
|
||||
const out = await minify(src, {
|
||||
compress: { passes: 3, pure_getters: true, unsafe_arrows: true },
|
||||
mangle: { properties: { regex: /^_/ } }, // 매 only _-prefixed
|
||||
format: { comments: false },
|
||||
sourceMap: { url: 'app.js.map' },
|
||||
});
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Vite production
|
||||
```javascript
|
||||
// vite.config.ts
|
||||
export default {
|
||||
build: {
|
||||
minify: 'esbuild', // or 'terser' for max
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
output: { manualChunks: { vendor: ['react', 'react-dom'] } },
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### CSS — Lightning CSS
|
||||
```javascript
|
||||
import { transform } from 'lightningcss';
|
||||
const { code } = transform({
|
||||
filename: 'style.css',
|
||||
code: Buffer.from(src),
|
||||
minify: true,
|
||||
targets: { chrome: 100 << 16, safari: 16 << 16 },
|
||||
});
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Sentry source map upload
|
||||
```bash
|
||||
sentry-cli sourcemaps inject ./dist
|
||||
sentry-cli sourcemaps upload --release "$VERSION" ./dist
|
||||
# 매 production 에 .map 의 ship 의 X — Sentry 의 server-side 보관
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### DCE / pure annotation
|
||||
```javascript
|
||||
// 매 tree shaker 에 hint
|
||||
const heavyConst = /*#__PURE__*/ buildHeavy();
|
||||
// 매 unused → bundle 에서 제거
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Tool |
|
||||
|---|---|
|
||||
| Default new project | esbuild / SWC |
|
||||
| Maximum compression | Terser (passes: 3) |
|
||||
| CSS | Lightning CSS |
|
||||
| HTML | html-minifier-terser |
|
||||
| Library publish | Rollup + esbuild minify |
|
||||
| Browser extension | esbuild (size budget) |
|
||||
|
||||
**기본값**: esbuild minify + tree shake + source maps + Sentry upload.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Build_Tools]] · [[Web_Performance]]
|
||||
- 변형: [[Tree_Shaking]] · [[Code_Splitting]] · [[Compression]]
|
||||
- 응용: [[Bundle_Analysis]] · [[Source_Maps]]
|
||||
- Adjacent: [[esbuild]] · [[Vite]] · [[Webpack]] · [[Rollup]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: build config 작성, minifier option tuning, bundle analysis.
|
||||
**언제 X**: 매 generated bundle 의 manual edit — 매 source 의 수정 후 rebuild.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No source map in prod**: 매 stack trace 의 obfuscated — debug 불가.
|
||||
- **Property mangle without test**: 매 `obj["field"]` access 의 break.
|
||||
- **Minify before bundling**: 매 cross-module DCE 의 손실.
|
||||
- **Comments preserved**: license 의 `/*! */` 만 keep, rest strip.
|
||||
- **One huge bundle**: code split 의 X — initial load 의 huge.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (esbuild docs, Terser README, Vite docs, Lightning CSS docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — esbuild/SWC/Terser/Lightning CSS patterns + DCE |
|
||||
|
||||
Reference in New Issue
Block a user