[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,96 +1,234 @@
|
||||
---
|
||||
id: wiki-2026-0508-zero-runtime-css-in-js
|
||||
title: Zero Runtime CSS in JS
|
||||
title: Zero-Runtime CSS-in-JS
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Zero-Runtime CSS-in-JS, Zero Runtime CSS, Static CSS-in-JS]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [css, css-in-js, build-time, zero-runtime, vanilla-extract, linaria]
|
||||
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
|
||||
---
|
||||
|
||||
# [[Zero-Runtime CSS-in-JS|Zero-runtime CSS-in-JS]]
|
||||
# Zero-Runtime CSS-in-JS
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Zero-runtime [[CSS-in-JS|CSS-in-JS]]는 브라우저에서 스타일을 처리하기 위한 JavaScript 런타임 오버헤드 없이, 빌드 타임에 정적 CSS를 생성하는 스타일링 패러다임이다 [1, 2]. 대표적인 도구인 `vanilla-extract`는 타입 안전(type-safe)한 스타일링을 제공하면서도 런타임 비용을 전혀 발생시키지 않는다 [1]. 이는 [[React Server Components|React Server Components]](RSC) 환경과 호환되지 않는 기존 런타임 CSS-in-JS의 한계를 극복하고 네이티브 CSS 수준의 성능을 달성하기 위한 핵심 대안으로 평가받는다 [1-3].
|
||||
## 매 한 줄
|
||||
> **"매 build time 에 CSS 로 추출 — runtime overhead 0"**. 매 styled-components/emotion 의 runtime injection 의 단점 (FCP 손실, hydration cost, RSC 비호환) 매 해결. 매 vanilla-extract (Mark Dalgleish), Linaria, Panda CSS, StyleX (Meta) 매 대표주자. 매 React Server Component 시대의 사실상 표준.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **등장 배경 및 RSC 호환성 문제:**
|
||||
기존의 [[Styled Components|Styled Components]]나 Emotion과 같은 CSS-in-JS 라이브러리들은 브라우저에서 JavaScript를 실행하여 CSS 문자열을 생성하고 주입하는 런타임 비용을 발생시켰다 [4, 5]. 이러한 방식은 특히 React Context에 의존하기 때문에, Context가 존재하지 않는 React [[Server Components|Server Components]](RSC) 환경에서는 근본적으로 호환되지 않는다는 큰 마찰을 빚게 되었다 [2, 3, 6]. 이러한 성능 및 호환성 문제를 해결하기 위해, 런타임 주입 오버헤드 없이 빌드 타임에 정적 CSS를 생성하는 zero-runtime 패러다임으로의 전환이 요구되었다 [2].
|
||||
## 매 핵심
|
||||
|
||||
* **주요 특징 및 `vanilla-extract`:**
|
||||
Zero-runtime CSS-in-JS는 JavaScript 최우선 스타일링의 개발자 인체공학적(ergonomics) 이점을 누리면서도 네이티브 CSS의 성능을 제공하는 것을 목표로 한다 [7]. 이 방식의 대표적인 라이브러리인 `vanilla-extract`는 빌드 타임에 [[CSS Modules|CSS Modules]]처럼 정적인 CSS를 생성하며, TypeScript를 활용해 완전히 타입 안전한(type-safe) 스타일링을 제로 런타임 오버헤드로 지원한다 [1]. 결과적으로 브라우저는 무거운 JavaScript 실행 없이 스타일을 기본적으로 파싱할 수 있게 된다 [2].
|
||||
### 매 runtime CSS-in-JS 의 문제
|
||||
- **Bundle size**: 매 emotion ~10KB, styled-components ~12KB minified.
|
||||
- **FCP 손실**: 매 JS 가 parse → execute → CSS inject → paint. 매 3-tier waterfall.
|
||||
- **Hydration cost**: 매 server-rendered CSS 와 client style 의 sync overhead.
|
||||
- **RSC 비호환**: 매 React Server Component 매 runtime context 없음 — 매 styled-components/emotion 매 client-only.
|
||||
- **Re-render cost**: 매 dynamic style prop 의 매 render 마다 hash + inject.
|
||||
|
||||
* **적용 시기 및 모범 사례:**
|
||||
다수의 테마를 관리해야 하는 대규모 디자인 시스템을 구축할 때 제로 런타임이면서 타입 안전성을 보장하는 `vanilla-extract`의 사용이 강력히 권장된다 [8]. 반면 [[Next.js App Router|Next.js App Router]]를 사용하는 신규 프로젝트의 경우, 런타임 방식의 CSS-in-JS 사용은 지양해야 하며 zero-runtime CSS-in-JS, [[Tailwind CSS|Tailwind CSS]] 또는 CSS Modules 중 하나를 채택하는 것이 아키텍처 관점에서의 모범 사례이다 [8].
|
||||
### 매 zero-runtime 의 해결
|
||||
- **Build-time extraction**: 매 .css.ts → .css 로 매 extract.
|
||||
- **Type safety**: 매 TypeScript 로 token, theme, variants 매 type-check.
|
||||
- **No runtime**: 매 0 KB 추가 — 매 static CSS 와 동일.
|
||||
- **RSC 호환**: 매 build-time output 이라 server/client 무관.
|
||||
- **CSS-only features**: 매 :hover, :focus, media query 매 CSS 자체 사용.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[React Server Components (RSC)|React Server Components (RSC]], CSS-in-JS, Tailwind CSS, [[Design Tokens|Design Tokens]], [[Next.js App Router|Next.js App Router]]
|
||||
- **Projects/Contexts:** [[vanilla-extract|vanilla-extract]], 대규모 디자인 시스템(Large DesignSystems)
|
||||
- **Contradictions/Notes:** 기존 런타임 CSS-in-JS(예: [[styled-components|styled-components]])는 컴포넌트 단위의 강력한 동적 스타일링 기능과 편리한 개발자 경험을 제공하지만 [4], [[Next.js|Next.js]] App Router와 같은 최신 RSC 환경에서는 심각한 성능 저하와 런타임 호환성 문제를 야기하므로 Zero-runtime CSS-in-JS나 Tailwind CSS로 마이그레이션하는 것이 대안으로 제시된다 [3, 8].
|
||||
### 매 응용
|
||||
1. Next.js App Router (RSC) 와 매 vanilla-extract pairing.
|
||||
2. Design system 의 token-based theming (light/dark, brand variant).
|
||||
3. Component library publishing (no runtime dependency).
|
||||
4. Performance-critical apps (e-commerce, content sites).
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-26*
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### vanilla-extract — basic style
|
||||
```ts
|
||||
// button.css.ts
|
||||
import { style } from '@vanilla-extract/css';
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
export const button = style({
|
||||
padding: '8px 16px',
|
||||
borderRadius: 4,
|
||||
background: 'blue',
|
||||
color: 'white',
|
||||
':hover': {
|
||||
background: 'darkblue',
|
||||
},
|
||||
});
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** 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)
|
||||
### vanilla-extract — variants (recipes)
|
||||
```ts
|
||||
// button.css.ts
|
||||
import { recipe } from '@vanilla-extract/recipes';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
export const button = recipe({
|
||||
base: { padding: 8, borderRadius: 4 },
|
||||
variants: {
|
||||
intent: {
|
||||
primary: { background: 'blue', color: 'white' },
|
||||
danger: { background: 'red', color: 'white' },
|
||||
},
|
||||
size: {
|
||||
sm: { fontSize: 12 },
|
||||
md: { fontSize: 14 },
|
||||
lg: { fontSize: 18 },
|
||||
},
|
||||
},
|
||||
defaultVariants: { intent: 'primary', size: 'md' },
|
||||
});
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// usage
|
||||
<button className={button({ intent: 'danger', size: 'lg' })}>Delete</button>
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### vanilla-extract — theme contract
|
||||
```ts
|
||||
// theme.css.ts
|
||||
import { createTheme, createThemeContract } from '@vanilla-extract/css';
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
export const vars = createThemeContract({
|
||||
color: { brand: null, text: null, bg: null },
|
||||
space: { sm: null, md: null, lg: null },
|
||||
});
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
export const lightTheme = createTheme(vars, {
|
||||
color: { brand: '#0066ff', text: '#000', bg: '#fff' },
|
||||
space: { sm: '4px', md: '8px', lg: '16px' },
|
||||
});
|
||||
|
||||
export const darkTheme = createTheme(vars, {
|
||||
color: { brand: '#3399ff', text: '#fff', bg: '#000' },
|
||||
space: { sm: '4px', md: '8px', lg: '16px' },
|
||||
});
|
||||
|
||||
// component uses vars
|
||||
import { vars } from './theme.css';
|
||||
const card = style({
|
||||
background: vars.color.bg,
|
||||
color: vars.color.text,
|
||||
padding: vars.space.md,
|
||||
});
|
||||
```
|
||||
|
||||
### Linaria — tagged template
|
||||
```ts
|
||||
import { css } from '@linaria/core';
|
||||
import { styled } from '@linaria/react';
|
||||
|
||||
const button = css`
|
||||
padding: 8px 16px;
|
||||
background: ${({ primary }) => primary ? 'blue' : 'gray'};
|
||||
`;
|
||||
|
||||
const Button = styled.button`
|
||||
border-radius: 4px;
|
||||
&:hover { opacity: 0.8; }
|
||||
`;
|
||||
// 매 build-time 에 CSS 추출, dynamic prop 매 CSS variable 로 변환.
|
||||
```
|
||||
|
||||
### Panda CSS — atomic + tokens
|
||||
```ts
|
||||
// panda.config.ts
|
||||
export default defineConfig({
|
||||
theme: {
|
||||
tokens: {
|
||||
colors: { brand: { value: '#0066ff' } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// component
|
||||
import { css } from 'styled-system/css';
|
||||
<div className={css({
|
||||
bg: 'brand',
|
||||
p: '4',
|
||||
rounded: 'md',
|
||||
_hover: { opacity: 0.8 },
|
||||
})}>
|
||||
Hello
|
||||
</div>
|
||||
// 매 build-time 에 atomic class generation. Tailwind-like.
|
||||
```
|
||||
|
||||
### StyleX (Meta) — atomic
|
||||
```ts
|
||||
import * as stylex from '@stylexjs/stylex';
|
||||
|
||||
const styles = stylex.create({
|
||||
button: {
|
||||
padding: '8px 16px',
|
||||
backgroundColor: { default: 'blue', ':hover': 'darkblue' },
|
||||
},
|
||||
});
|
||||
|
||||
<button {...stylex.props(styles.button)}>Click</button>
|
||||
// 매 Meta Facebook/Instagram 사용. 매 atomic class deduplication.
|
||||
```
|
||||
|
||||
### Migration — emotion → vanilla-extract
|
||||
```ts
|
||||
// Before (emotion)
|
||||
const Button = styled.button`
|
||||
padding: ${props => props.size === 'lg' ? '16px' : '8px'};
|
||||
`;
|
||||
|
||||
// After (vanilla-extract recipes)
|
||||
const button = recipe({
|
||||
base: {},
|
||||
variants: {
|
||||
size: { sm: { padding: 8 }, lg: { padding: 16 } },
|
||||
},
|
||||
});
|
||||
const Button = ({ size, ...rest }) => <button className={button({ size })} {...rest} />;
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Next.js App Router (RSC) | vanilla-extract or Panda CSS. |
|
||||
| TypeScript theme system | vanilla-extract (createThemeContract). |
|
||||
| Tailwind-style atomic | Panda CSS or StyleX. |
|
||||
| Existing styled-components codebase | Linaria (similar API, build-time). |
|
||||
| Component library 배포 | vanilla-extract (zero runtime dep). |
|
||||
| Quick prototype | Tailwind (no build setup) or emotion. |
|
||||
|
||||
**기본값**: vanilla-extract (Next.js + RSC), Panda CSS (atomic), Linaria (migration).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[CSS-in-JS]] · [[Build-time Optimization]]
|
||||
- 변형: [[vanilla-extract]] · [[Linaria]] · [[Panda CSS]] · [[StyleX]]
|
||||
- 응용: [[Design System]] · [[React Server Components]] · [[Next.js App Router]]
|
||||
- Adjacent: [[Tailwind CSS]] · [[CSS Modules]] · [[styled-components]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Next.js App Router (RSC) 의, performance-critical site, design system 의 type-safe theming, component library 배포 의.
|
||||
**언제 X**: 매 highly dynamic runtime style (theme switcher 매 CSS var 로 가능 — 그 외 의), 매 prototype 단계의 (Tailwind 매 빠름).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Runtime variable 을 build-time 으로 expect**: 매 `style({ color: dynamicVar })` — `dynamicVar` 매 build time 의 evaluable 해야. Runtime value 매 CSS variable 로.
|
||||
- **emotion + RSC 혼합**: 매 RSC 에서 emotion `css` prop X. 매 Server component 매 zero-runtime 만.
|
||||
- **css.ts 의 conditional logic**: 매 `if (process.env.NODE_ENV)` 매 build-time 에 evaluated — 매 runtime 변경 X.
|
||||
- **Import side effect 망각**: 매 vanilla-extract `*.css.ts` import 가 CSS 추출 trigger — tree-shake 의 영향.
|
||||
- **Tailwind 와 zero-runtime 의 비교 오류**: 매 Tailwind 도 zero-runtime — 단지 매 CSS-in-JS 가 아닌 utility-first.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (vanilla-extract docs, Linaria docs, Panda CSS docs, StyleX official).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — vanilla-extract, Linaria, Panda CSS, StyleX patterns + RSC compatibility 추가 |
|
||||
|
||||
Reference in New Issue
Block a user