Files
2nd/10_Wiki/Topics/Frontend/Zero-Runtime CSS-in-JS.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

235 lines
7.3 KiB
Markdown

---
id: wiki-2026-0508-zero-runtime-css-in-js
title: Zero-Runtime CSS-in-JS
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Zero-Runtime CSS-in-JS, Zero Runtime CSS, Static CSS-in-JS]
duplicate_of: none
source_trust_level: A
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-10
github_commit: pending
tech_stack:
language: typescript
framework: vanilla-extract
---
# Zero-Runtime CSS-in-JS
## 매 한 줄
> **"매 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 시대의 사실상 표준.
## 매 핵심
### 매 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.
### 매 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 자체 사용.
### 매 응용
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).
## 💻 패턴
### vanilla-extract — basic style
```ts
// button.css.ts
import { style } from '@vanilla-extract/css';
export const button = style({
padding: '8px 16px',
borderRadius: 4,
background: 'blue',
color: 'white',
':hover': {
background: 'darkblue',
},
});
// button.tsx
import { button } from './button.css';
export const Button = (props) => <button className={button} {...props} />;
```
### vanilla-extract — variants (recipes)
```ts
// button.css.ts
import { recipe } from '@vanilla-extract/recipes';
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' },
});
// usage
<button className={button({ intent: 'danger', size: 'lg' })}>Delete</button>
```
### vanilla-extract — theme contract
```ts
// theme.css.ts
import { createTheme, createThemeContract } from '@vanilla-extract/css';
export const vars = createThemeContract({
color: { brand: null, text: null, bg: null },
space: { sm: null, md: null, lg: null },
});
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_Architecture_and_Styling|CSS-in-JS]]
- 변형: [[vanilla-extract]] · [[Panda CSS]]
- 응용: [[Design System]] · [[React Server Components]]
- Adjacent: [[CSS_Architecture_and_Styling|Tailwind CSS]] · [[CSS Modules]] · [[Styled_Components|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 추가 |