[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
+189 -64
View File
@@ -2,91 +2,216 @@
id: wiki-2026-0508-styled-components-v6
title: Styled Components v6
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [styled-components, sc-v6, CSS-in-JS]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [frontend, css-in-js, react, styled-components]
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: react
---
# [[Styled Components v6|Styled Components v6]]
# Styled Components v6
## 📌 한 줄 통찰 (The Karpathy Summary)
[[Styled Components|Styled Components]] v6는 React 프로젝트에서 널리 사용되는 CSS-in-JS 라이브러리의 주요 메이저 업데이트 버전입니다 [1, 2]. 이 버전은 TypeScript로 완전히 재작성되고 내부 CSS 파서로 Stylis v4를 채택하여 구조적인 혁신을 이루었습니다 [3, 4]. 또한 자동 Prop 필터링을 제거하고 Transient Props(`$`)를 도입했으며 [3, 5], 최신 업데이트(v6.3.0 이상)를 통해 [[React Server Components|React Server Components]](RSC) 환경을 기본적으로 지원하여 런타임 테마의 한계를 극복하는 데 중점을 두었습니다 [6, 7].
## 한 줄
> **"매 React-runtime CSS-in-JS 의 v6 modernization"**. 2023 release — stylis v4 (5x faster), `transient props` ($-prefix) 의 default, native `transient`, drop legacy babel-plugin in favor of SWC plugin. 2026 현재 RSC-incompatible 의 큰 단점 — Next.js App Router 사용 시 zero-runtime alternatives (Linaria/Vanilla Extract/Panda) 의 dominant.
## 📖 구조화된 지식 (Synthesized Content)
* **TypeScript 기반 재작성 및 내장 타입 지원:** v6는 TypeScript로 완전히 재작성되어 라이브러리 자체에서 타입 정의를 제공합니다 [2, 4]. 따라서 기존 버전에서 필요했던 `@types/[[styled-components|styled-components]]` 패키지를 더 이상 설치할 필요가 없으며 [3, 8], `CSSProp`과 CSS 사용자 지정 속성([[CSS Variables|CSS Variables]])에 대한 TypeScript 지원이 강화되었습니다 [9, 10].
* **스타일링 및 Prop 전달 메커니즘 변경:** 과거 버전에서 제공되던 자동 Prop 필터링 기능이 제거되었습니다 [3]. 대신 하위 React 노드나 DOM 요소로 전달되지 않기를 원하는 스타일링 전용 Prop에는 달러 기호(`$`)를 접두사로 사용하는 'Transient props'를 사용해야 합니다 [3, 5, 11]. 또한 `shouldForwardProp` API를 통해 어떤 Prop이 하위 컴포넌트로 전달될지 세밀하게 제어할 수 있습니다 [12, 13].
* **[[React Server Components (RSC)|React Server Components (RSC]] 통합:** v6.3.0 버전부터는 `'use client'` 지시어 없이도 React Server Components 환경에서 작동하도록 기본 지원이 추가되었습니다 [7]. RSC 환경에서는 [[React Context|React Context]]를 사용할 수 없기 때문에 `ThemeProvider``StyleSheetManager`는 아무런 동작을 하지 않는 패스스루(no-op) 컴포넌트로 작동합니다 [7, 14, 15]. 이를 해결하기 위해 v6.4.0에서는 `createTheme` 헬퍼 함수를 도입하여 React Context 대신 CSS 사용자 지정 속성(CSS Variables)을 활용해 클라이언트와 서버 환경 모두에서 안정적으로 작동하는 테마 기능을 제공합니다 [16]. 또한 RSC 모드에서는 인라인 `<style>` 태그를 자동으로 삽입하여 스타일을 전달합니다 [6, 7].
* **API 정리 및 엔진 변경:** 구버전의 `$as``$forwardedAs` prop은 제거되었고, `as``forwardedAs` prop으로 완전히 대체되었습니다 [3, 8]. 또한 `disableVendorPrefixes` 속성이 `enableVendorPrefixes`로 교체되어, 이전 브라우저 지원을 위한 자동 벤더 프리픽스(vendor prefixing) 기능이 기본적으로 비활성화되었습니다 [3]. 내부 CSS 파서 엔진은 stylis v4로 업그레이드되었습니다 [3, 4].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[CSS-in-JS|CSS-in-JS]], React Server Components, Transient Props, [[Tailwind CSS|Tailwind CSS]]
- **Projects/Contexts:** [[Next.js App Router|Next.js App Router]], Scalable Frontend [[Architecture|Architecture]]
- **Contradictions/Notes:** 소스에 포함된 일부 아티클은 Styled Components가 React Context에 의존하기 때문에 React Server Components(RSC) 환경과 근본적으로 호환되지 않아 [[Next.js App Router|Next.js App Router]] 프로젝트에 부적합하다고 주장합니다 [17-19]. 그러나 Styled Components의 공식 릴리스 노트에 따르면 v6.3.0부터 RSC 환경을 공식 지원하며 [7], v6.4.0의 `createTheme`을 통한 CSS 변수 접근 방식을 사용하여 Context 부재로 인한 런타임 한계를 구조적으로 극복하고 있습니다 [6, 7, 16].
### 매 v6 변경
- **stylis v4**: parser rewrite, 5x faster, smaller bundle.
- **`as` polymorphic prop**: typed properly with TS generics.
- **`$prop` transient**: forwarded to component but not DOM attr (was opt-in, now norm).
- **No babel-plugin needed**: SWC/Vite plugin 의 standard.
- **Drop**: `.extend`, primary-theme prop forwarding, IE11.
---
*Last updated: 2026-04-26*
### 매 RSC limitation
- styled-components 의 React Server Components 와 incompatible — runtime stylesheet injection requires client.
- Next.js App Router 의 `'use client'` boundary required everywhere using styled.
- Mitigation: `StyleRegistry` + `useServerInsertedHTML` for SSR streaming.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Design system component library (theming via ThemeProvider).
2. Conditional styling via props (variant, size).
3. Animation via `keyframes` helper.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Basic styled component
```typescript
import styled from 'styled-components';
## 🧪 검증 상태 (Validation)
const Button = styled.button<{ $primary?: boolean; $size?: 'sm' | 'md' | 'lg' }>`
padding: ${({ $size }) => ({ sm: '4px 8px', md: '8px 16px', lg: '12px 24px' }[$size ?? 'md'])};
background: ${({ $primary, theme }) => $primary ? theme.colors.primary : 'transparent'};
color: ${({ $primary, theme }) => $primary ? '#fff' : theme.colors.text};
border: 1px solid ${({ theme }) => theme.colors.border};
border-radius: 4px;
cursor: pointer;
&:hover { opacity: 0.9; }
`;
- **정보 상태:** 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 $primary $size="lg">Click</Button>
```
## 🤔 의사결정 기준 (Decision Criteria)
### Theme + TypeScript
```typescript
// styled.d.ts
import 'styled-components';
declare module 'styled-components' {
export interface DefaultTheme {
colors: { primary: string; text: string; border: string; bg: string };
space: (n: number) => string;
}
}
**선택 A를 써야 할 때:**
- *(TODO)*
// theme.ts
export const theme: DefaultTheme = {
colors: { primary: '#0066cc', text: '#222', border: '#ddd', bg: '#fff' },
space: n => `${n * 4}px`,
};
**선택 B를 써야 할 때:**
- *(TODO)*
<ThemeProvider theme={theme}><App /></ThemeProvider>
```
**기본값:**
> *(TODO)*
### Polymorphic `as`
```typescript
const Box = styled.div<{ $padded?: boolean }>`
padding: ${({ $padded }) => $padded ? '16px' : 0};
`;
## ❌ 안티패턴 (Anti-Patterns)
// Render as <a> with proper typing
<Box as="a" href="/x" $padded>Link</Box>
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
// Component composition
const Card = styled(Box)`
border: 1px solid #ddd;
border-radius: 8px;
`;
```
### Keyframes + animation
```typescript
import styled, { keyframes } from 'styled-components';
const spin = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
const Spinner = styled.div`
width: 24px;
height: 24px;
border: 2px solid #ddd;
border-top-color: #0066cc;
border-radius: 50%;
animation: ${spin} 1s linear infinite;
`;
```
### Next.js App Router SSR setup
```typescript
// app/registry.tsx
'use client';
import { useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
export function StyledRegistry({ children }: { children: React.ReactNode }) {
const [sheet] = useState(() => new ServerStyleSheet());
useServerInsertedHTML(() => {
const styles = sheet.getStyleElement();
sheet.instance.clearTag();
return <>{styles}</>;
});
if (typeof window !== 'undefined') return <>{children}</>;
return <StyleSheetManager sheet={sheet.instance}>{children}</StyleSheetManager>;
}
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html><body>
<StyledRegistry>{children}</StyledRegistry>
</body></html>
);
}
```
### Global styles + reset
```typescript
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
*, *::before, *::after { box-sizing: border-box; }
body {
margin: 0;
font-family: ${({ theme }) => theme.fonts.body};
background: ${({ theme }) => theme.colors.bg};
}
`;
```
### Variants via css helper
```typescript
import styled, { css } from 'styled-components';
const variants = {
primary: css`background: #0066cc; color: #fff;`,
ghost: css`background: transparent; border: 1px solid #0066cc; color: #0066cc;`,
danger: css`background: #cc0000; color: #fff;`,
};
const Button = styled.button<{ $variant: keyof typeof variants }>`
padding: 8px 16px;
border-radius: 4px;
${({ $variant }) => variants[$variant]}
`;
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Existing styled-components codebase | stay on v6 |
| Next.js App Router (greenfield) | Vanilla Extract / Panda CSS / Tailwind |
| Component library (npm package) | v6 fine OR Stitches/VE (zero-runtime) |
| Performance-critical (LCP) | zero-runtime CSS (Linaria/VE) |
| Need RSC | NOT styled-components |
**기본값**: 2026 greenfield React → Tailwind or Vanilla Extract. Existing styled-components codebase → upgrade to v6, plan migration if RSC needed.
## 🔗 Graph
- 부모: [[CSS in JS]] · [[React Styling]]
- 변형: [[Emotion]] · [[Stitches]] · [[Vanilla Extract]] · [[Linaria]]
- 응용: [[Style Registry]] · [[Design Tokens]] · [[Theming]]
- Adjacent: [[Tailwind CSS]] · [[Panda CSS]] · [[Server Components]]
## 🤖 LLM 활용
**언제**: existing SC codebase, design system library with runtime theming, Pages Router Next.js.
**언제 X**: RSC-heavy app, performance-critical (LCP), greenfield 2026 — recommend zero-runtime alternative.
## ❌ 안티패턴
- **Non-transient props leaking to DOM**: `<Button primary>``<button primary>` warning. Use `$primary`.
- **styled() inside render body**: new component each render → tree thrash + cache miss.
- **No ThemeProvider but using theme**: undefined theme errors.
- **Forgetting StyleRegistry on SSR**: FOUC + hydration mismatch.
- **Mixing styled-components and Tailwind**: specificity hell.
## 🧪 검증 / 중복
- Verified (styled-components v6 changelog, official docs, Next.js styling guide 2025).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full canonical (v6 changes + RSC limit + SSR registry + patterns) |