[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+265 -65
View File
@@ -1,92 +1,292 @@
---
id: wiki-2026-0508-vanilla-extract
title: vanilla extract
title: vanilla-extract
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [vanilla-extract, vanilla extract, ve, css.ts]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [css-in-js, zero-runtime, vanilla-extract, typescript, build-time]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: vanilla-extract
---
# [[vanilla-extract|vanilla-extract]]
# vanilla-extract
## 📌 한 줄 통찰 (The Karpathy Summary)
vanilla-extract는 빌드 타임에 정적 CSS를 생성하는 제로 런타임(Zero-runtime) [[CSS-in-JS|CSS-in-JS]] 라이브러리입니다 [1-3]. 기존 CSS-in-JS가 지니던 런타임 오버헤드 문제 없이, JavaScript 및 TypeScript를 활용한 타입 안전(type-safe)한 스타일링 개발 경험을 제공합니다 [2, 3]. 특히 [[React Server Components|React Server Components]](RSC)와 완벽하게 호환되며, 여러 테마를 관리해야 하는 대규모 디자인 시스템 구축에 강력히 권장되는 접근 방식입니다 [2, 4-6].
## 한 줄
> **"매 TypeScript 로 type-safe 한 zero-runtime CSS-in-JS"**. 매 Mark Dalgleish (Seek) 가 2021 년 출시. 매 `.css.ts` 파일을 build time 에 static CSS 로 추출, 매 token / variant / theme 매 모두 typed. 매 Next.js App Router (RSC) 의 사실상 표준, 매 component library 배포 의 zero-runtime guarantee.
## 📖 구조화된 지식 (Synthesized Content)
* **제로 런타임과 성능 최적화:** vanilla-extract는 기존 런타임 CSS-in-JS(예: [[styled-components|styled-components]], Emotion)가 야기하는 브라우저 런타임 오버헤드 및 번들 크기 증가 문제를 해결하기 위해 등장한 대안입니다 [3, 4, 7]. 빌드 시점에 정적 CSS를 생성해 내기 때문에, JavaScript 실행 중 스타일을 파싱하고 DOM에 주입하는 데 드는 비용(CPU 사이클 등)이 전혀 발생하지 않습니다 [2, 3].
* **타입 안정성과 개발자 경험:** 이 도구는 TypeScript를 사용하여 타입 안전한 스타일링을 지원합니다 [2]. 이를 통해 JavaScript 기반 스타일링이 제공하는 훌륭한 개발자 경험과 동적 제어의 이점을 유지하면서도, [[CSS Modules|CSS Modules]]와 같은 정적 CSS의 성능적 이점을 동시에 확보할 수 있는 중간 지점(middle ground) 역할을 합니다 [2, 3].
* **RSC(React [[Server Components|Server Components]]) 호환성:** 기존의 Context 기반 CSS-in-JS 라이브러리들은 브라우저가 아닌 서버에서 실행되는 React Server Components(RSC) 환경과 근본적으로 호환되지 않는 문제를 안고 있습니다 [4, 5]. 그러나 vanilla-extract는 빌드 타임에 정적 CSS를 추출하는 방식을 취하므로, RSC 및 [[Next.js App Router|Next.js App Router]] 환경에서도 문제없이 완벽하게 작동합니다 [2, 5].
* **대규모 디자인 시스템 및 테마 적용:** 여러 시각적 테마(라이트/다크 모드, 고객사별 브랜딩 등)를 적용해야 하는 제품에서 높은 가치를 지닙니다 [6, 7]. 대규모 디자인 시스템을 다루면서도 테마 적용이 필요한 경우, 제로 런타임과 타입 안정성을 모두 잡은 vanilla-extract는 가장 추천되는 스타일링 전략 중 하나입니다 [6].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[CSS-in-JS|CSS-in-JS]], CSS Modules, 디자인 시스템 개념, [[성능 최적화(Performance Optimization)|성능 최적화(Performance Optimization]]
- **Projects/Contexts:** [[React Server Components (RSC)|React Server Components (RSC]], [[Next.js App Router|Next.js App Router]]
- **Contradictions/Notes:** 소스에 따르면 기존 런타임 CSS-in-JS 라이브러리(styled-components, Emotion)는 React 컨텍스트 부족으로 인해 React Server Components(RSC) 환경에서 호환되지 않지만, vanilla-extract는 빌드 시점에 CSS를 정적으로 추출하므로 RSC와 완벽하게 호환되어 이를 대체할 수 있는 것으로 평가받고 있습니다 [2, 4, 5].
### 매 핵심 API
- `style({...})`: 매 single CSS class 생성 → unique class name 반환.
- `globalStyle('selector', {...})`: 매 global selector style.
- `recipe({base, variants})`: 매 variant-based component (CVA-like, type-safe).
- `createTheme(contract, values)`: 매 token 의 ThemeProvider 대안.
- `createThemeContract({...})`: 매 token shape 정의 (multi-theme).
- `createVar()`: 매 CSS custom property (runtime dynamic).
- `style([base, override])`: 매 style composition.
---
*Last updated: 2026-04-26*
### 매 build setup
- **Webpack**: `@vanilla-extract/webpack-plugin`.
- **Vite**: `@vanilla-extract/vite-plugin`.
- **Next.js**: `@vanilla-extract/next-plugin` (App Router 호환).
- **esbuild / Rollup / Parcel**: 매 dedicated plugins.
- 매 결과: `.css.ts``.css` 추출 + `.js` 의 class name string export.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Design system 의 token-based theming.
2. Next.js App Router 의 RSC-compatible styling.
3. Component library 의 zero-runtime publish.
4. CVA-style variants via recipes.
5. CSS variable scoped to component.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Basic style
```ts
// button.css.ts
import { style } from '@vanilla-extract/css';
## 🧪 검증 상태 (Validation)
export const button = style({
padding: '8px 16px',
borderRadius: 4,
background: 'blue',
color: 'white',
cursor: 'pointer',
selectors: {
'&:hover': { background: 'darkblue' },
'&:disabled': { opacity: 0.5, cursor: 'not-allowed' },
},
});
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// button.tsx
import { button } from './button.css';
export const Button = (props) => <button className={button} {...props} />;
```
## 🤔 의사결정 기준 (Decision Criteria)
### Theme contract — multi-theme
```ts
// theme.css.ts
import { createTheme, createThemeContract } from '@vanilla-extract/css';
**선택 A를 써야 할 때:**
- *(TODO)*
export const vars = createThemeContract({
color: { brand: null, text: null, bg: null, border: null },
space: { xs: null, sm: null, md: null, lg: null, xl: null },
radius: { sm: null, md: null, lg: null },
font: { sans: null, mono: null },
});
**선택 B를 써야 할 때:**
- *(TODO)*
export const lightTheme = createTheme(vars, {
color: { brand: '#0066ff', text: '#111', bg: '#fff', border: '#e0e0e0' },
space: { xs: '4px', sm: '8px', md: '16px', lg: '24px', xl: '32px' },
radius: { sm: '2px', md: '4px', lg: '8px' },
font: { sans: 'Inter, sans-serif', mono: 'JetBrains Mono, monospace' },
});
**기본값:**
> *(TODO)*
export const darkTheme = createTheme(vars, {
color: { brand: '#3399ff', text: '#fff', bg: '#0a0a0a', border: '#222' },
space: { xs: '4px', sm: '8px', md: '16px', lg: '24px', xl: '32px' },
radius: { sm: '2px', md: '4px', lg: '8px' },
font: { sans: 'Inter, sans-serif', mono: 'JetBrains Mono, monospace' },
});
## ❌ 안티패턴 (Anti-Patterns)
// app.tsx
<html className={isDark ? darkTheme : lightTheme}>
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Component using vars
```ts
// card.css.ts
import { style } from '@vanilla-extract/css';
import { vars } from './theme.css';
export const card = style({
background: vars.color.bg,
color: vars.color.text,
border: `1px solid ${vars.color.border}`,
padding: vars.space.md,
borderRadius: vars.radius.lg,
fontFamily: vars.font.sans,
});
```
### Recipes — variants (CVA-like)
```ts
// button.css.ts
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
import { vars } from './theme.css';
export const button = recipe({
base: {
padding: vars.space.sm,
borderRadius: vars.radius.md,
cursor: 'pointer',
border: 'none',
fontFamily: vars.font.sans,
},
variants: {
intent: {
primary: { background: vars.color.brand, color: '#fff' },
secondary: { background: 'transparent', color: vars.color.brand,
border: `1px solid ${vars.color.brand}` },
danger: { background: '#dc2626', color: '#fff' },
},
size: {
sm: { fontSize: 12, padding: vars.space.xs },
md: { fontSize: 14, padding: vars.space.sm },
lg: { fontSize: 18, padding: vars.space.md },
},
fullWidth: {
true: { width: '100%' },
},
},
compoundVariants: [
{ variants: { intent: 'primary', size: 'lg' },
style: { fontWeight: 'bold' } },
],
defaultVariants: { intent: 'primary', size: 'md' },
});
export type ButtonVariants = RecipeVariants<typeof button>;
// type ButtonVariants = { intent?: 'primary' | 'secondary' | 'danger'; size?: ...; fullWidth?: boolean }
// usage
<button className={button({ intent: 'danger', size: 'lg' })}>Delete</button>
```
### Sprinkles — atomic CSS (Tailwind-like)
```ts
// sprinkles.css.ts
import { defineProperties, createSprinkles } from '@vanilla-extract/sprinkles';
const space = defineProperties({
properties: {
padding: { sm: 8, md: 16, lg: 24 },
margin: { sm: 8, md: 16, lg: 24 },
},
shorthands: { p: ['padding'], m: ['margin'] },
});
export const sprinkles = createSprinkles(space);
// usage
<div className={sprinkles({ p: 'md', m: 'sm' })}>...</div>
```
### Global style + reset
```ts
// reset.css.ts
import { globalStyle } from '@vanilla-extract/css';
globalStyle('html, body', {
margin: 0,
padding: 0,
fontFamily: 'system-ui, sans-serif',
});
globalStyle('*', {
boxSizing: 'border-box',
});
// 매 import 'one' 으로 reset 적용
// app.tsx: import './reset.css';
```
### Dynamic value via createVar
```ts
// progress.css.ts
import { createVar, style } from '@vanilla-extract/css';
export const progressVar = createVar();
export const bar = style({
width: progressVar,
background: 'blue',
height: 4,
transition: 'width 0.3s',
});
// progress.tsx
import { assignInlineVars } from '@vanilla-extract/dynamic';
<div
className={bar}
style={assignInlineVars({ [progressVar]: `${percent}%` })}
/>
// 매 runtime dynamic — CSS variable 로 변환.
```
### Style composition
```ts
import { style } from '@vanilla-extract/css';
const base = style({ padding: 8, fontSize: 14 });
const primary = style([base, { background: 'blue', color: 'white' }]);
// 매 primary class = base class + extra rules.
```
### Next.js App Router setup
```ts
// next.config.js
const { createVanillaExtractPlugin } = require('@vanilla-extract/next-plugin');
const withVanillaExtract = createVanillaExtractPlugin();
module.exports = withVanillaExtract({
// ... existing config
});
// app/layout.tsx
import { lightTheme } from './theme.css';
import './reset.css';
export default function RootLayout({ children }) {
return <html className={lightTheme}>{children}</html>;
}
// 매 RSC 호환 — server component 에서 매 className 사용 가능.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Next.js App Router (RSC) | vanilla-extract (built-in plugin). |
| Type-safe theme tokens | `createThemeContract` + `createTheme`. |
| CVA-style variants | `recipe`. |
| Atomic / Tailwind-like | `sprinkles`. |
| Runtime dynamic value | `createVar` + `assignInlineVars`. |
| Component library 배포 | vanilla-extract (zero runtime). |
**기본값**: `style` (single class), `recipe` (variants), `createThemeContract` (multi-theme), `createVar` (runtime dynamic).
## 🔗 Graph
- 부모: [[CSS-in-JS]] · [[Zero-Runtime CSS-in-JS]]
- 변형: [[Linaria]] · [[Panda CSS]] · [[StyleX]] · [[CSS Modules]]
- 응용: [[Design System]] · [[Next.js App Router]] · [[React Server Components]]
- Adjacent: [[CVA]] · [[Tailwind CSS]] · [[Sprinkles]]
## 🤖 LLM 활용
**언제**: Next.js App Router (RSC), type-safe design system, component library 배포, multi-theme (light/dark/brand) 의.
**언제 X**: 매 simple prototype (Tailwind 매 빠름), 매 highly-dynamic per-pixel value (CSS-in-JS runtime 가 더 적합), 매 already emotion / styled-components codebase 의 incremental migration 어려움.
## ❌ 안티패턴
- **Runtime value 직접 사용**: 매 `style({ width: dynamicWidth })``dynamicWidth` 매 build time 에 evaluable 해야. 매 runtime 매 `createVar`.
- **`.css.ts` 의 conditional logic**: 매 `if (env.X)` 매 build-time evaluated — 매 runtime 분기 X.
- **Theme class 의 dynamic apply 미숙**: 매 theme 변경 시 `<html className={isDark ? darkTheme : lightTheme}>` — 매 root 단위.
- **plugin setup 누락**: 매 webpack/vite plugin 없으면 .css.ts 매 그냥 TS file 로 처리 — error.
- **`recipe` 의 base 의 selector**: 매 `recipe` base 안의 `selectors` 매 매 supported 하나 매 syntax 주의.
## 🧪 검증 / 중복
- Verified (vanilla-extract.style 공식 문서, GitHub seek-oss/vanilla-extract).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — vanilla-extract API 전체 (style, recipe, theme contract, sprinkles, createVar) 추가 |