[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
@@ -2,103 +2,283 @@
id: wiki-2026-0508-style-dictionary-pipelines
title: Style Dictionary Pipelines
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Style Dictionary, Design Token Pipeline, Token Build Pipeline]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [design-tokens, style-dictionary, design-system, ci-cd, frontend]
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: Style Dictionary 4.x
---
# [[Style Dictionary Pipelines|Style Dictionary Pipelines]]
# Style Dictionary Pipelines
## 📌 한 줄 통찰 (The Karpathy Summary)
[[Style Dictionary|Style Dictionary]] 파이프라인은 플랫폼에 구애받지 않는 디자인 토큰(JSON 등)을 구문 분석하고 변환하여 iOS, Android, CSS, JS 등 다양한 플랫폼에 맞는 코드로 내보내는 자동화된 빌드 시스템 워크플로우를 의미합니다[1-3]. 이 파이프라인을 통해 여러 플랫폼에서 디자인 값의 '단일 진실 공급원([[Single_Source_of_Truth|Single Source of Truth]])'을 구축하여 수동 오류를 없애고 시각적 일관성을 유지할 수 있습니다[3]. "예쁘게"를 넘어 확장성과 "유지보수성"을 달성하기 위한 대규모 디자인 시스템 아키텍처의 핵심 도구로 작용합니다[3, 4].
## 한 줄
> **"매 Style Dictionary 는 design token (JSON) 을 platform 별 산출물 (CSS/iOS/Android/JSON) 로 transform 하는 build tool"**. Amazon 발 (2017), v4 (2024) 에서 ESM + DTCG 표준 지원. 2026 기준 Figma Variables → Tokens Studio → Style Dictionary → multi-platform output 의 typical pipeline. CI/CD 통합으로 매 design 변경 → automatic code propagation.
## 📖 구조화된 지식 (Synthesized Content)
* **빌드 시스템의 역할 및 작동 원리**
* Style Dictionary는 [[Nodejs|Nodejs]]와 브라우저 환경에서 실행되는 빌드 시스템입니다[2].
* 구성(configuration)에 정의된 `source``include` 배열을 통해 여러 개의 디자인 토큰 파일(JSON, JSONC, ES Modules 등)을 찾아 심층 병합(deep merge)을 수행합니다[5-7].
* 파일 병합 과정 중 점 표기법(dot-notation)을 사용한 참조(Aliasing, 예: `{size.font.medium}`)를 올바르게 해석하고, 충돌(Collision) 발생 시 나중에 선언된 파일이 우선순위를 갖도록 처리하여 기본 테마를 쉽게 덮어쓸 수 있는 유연성을 제공합니다[6-9].
## 매 핵심
* **디자인-투-코드(Design-to-Code) 워크플로우**
* 모던 디자인 토큰 워크플로우는 일반적으로 다음 파이프라인을 거칩니다[10].
1. **Design**: [[Figma|Figma]] 등의 도구에서 플러그인(예: Tokens Studio)을 사용하여 토큰을 생성합니다.
2. **Export**: 디자인 토큰을 JSON 포맷으로 내보냅니다.
3. **Transform**: Style Dictionary를 사용하여 이러한 데이터를 각 플랫폼 파일(웹용 CSS 변수, Android용 XML, iOS용 Swift 등)로 자동 변환합니다[3, 10].
4. **Distribute**: 변환된 결과물을 npm 패키지 등으로 배포하거나 저장소에 포함합니다.
5. **Consume & Update**: 웹, iOS, Android 애플리케이션에서 이를 가져와 사용하며, 디자인 도구에서 변경 사항이 발생하면 파이프라인을 통해 모든 시스템에 업데이트가 자동으로 전파됩니다.
### 매 token 계층
- **Reference (primitive)**: `color.blue.500`, `size.4`
- **System (alias)**: `color.brand.primary``{color.blue.500}`
- **Component**: `button.bg.primary``{color.brand.primary}`
* **유지보수성(Maintainability)과 아키텍처적 가치**
* 대규모 엔터프라이즈 환경에서는 디자이너가 Figma에서 '프라이머리 블루' 색상을 업데이트할 때, 이 변경 사항이 Style Dictionary와 CI/CD 파이프라인을 통해 수많은 애플리케이션 컴포넌트로 자동 전파되도록 구성합니다[11, 12].
* 이러한 자동화 파이프라인은 스타일링 프로세스에서 가장 반복적이고 오류가 발생하기 쉬운 인적 개입을 제거하므로 진정한 의미의 '유지보수성'을 달성하는 궁극적인 표현 방식으로 평가받습니다[12].
### 매 transform / format
- **transform**: token value 변환 (px→rem, hex→rgba)
- **format**: output file 생성 (CSS vars, TS, iOS swift, Android XML)
- **filter**: token subset 선택
- **action**: 매 build side-effect (e.g. asset copy)
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[디자인 시스템 (Design Systems)|디자인 시스템(DesignSystems]], 디자인 토큰(Design Tokens), [[유지보수성(Maintainability)|유지보수성(Maintainability]]
- **Projects/Contexts:** [[대규모 프론트엔드 아키텍처(Large-Scale Frontend Architecture)|대규모 프론트엔드 아키텍처(Large-Scale Frontend Architecture]], [[크로스 플랫폼 UI 개발(Cross-Platform UI Development)|크로스 플랫폼 UI 개발(Cross-Platform UI Development]]
- **Contradictions/Notes:** Figma와 같은 기본 디자인 애플리케이션은 디자인 토큰 관리를 위한 인앱 솔루션을 완벽하게 지원하지 않는 한계를 가집니다. 따라서 개발자와 디자이너 사이의 간극을 메우고 동기화된 통신을 허용하기 위해 Style Dictionary를 활용한 파이프라인 같은 서드파티 해결책에 전적으로 의존하고 있습니다[13].
### 매 응용
1. Multi-platform design system (web + iOS + Android).
2. Theming (light/dark, brand variants).
3. Figma → code synchronization.
4. Component library token consumer.
---
*Last updated: 2026-04-26*
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(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
### Token JSON (DTCG format)
```json
// tokens/color.json
{
"color": {
"blue": {
"500": { "$value": "#3b82f6", "$type": "color" },
"600": { "$value": "#2563eb", "$type": "color" }
},
"brand": {
"primary": { "$value": "{color.blue.500}", "$type": "color" }
}
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### config.ts (v4)
```typescript
// config.ts
import StyleDictionary from "style-dictionary";
**선택 A를 써야 할 때:**
- *(TODO)*
const sd = new StyleDictionary({
source: ["tokens/**/*.json"],
platforms: {
css: {
transformGroup: "css",
buildPath: "build/css/",
files: [{ destination: "tokens.css", format: "css/variables" }],
},
ts: {
transformGroup: "js",
buildPath: "build/ts/",
files: [
{ destination: "tokens.ts", format: "javascript/es6" },
{ destination: "tokens.d.ts", format: "typescript/es6-declarations" },
],
},
ios: {
transformGroup: "ios-swift",
buildPath: "build/ios/",
files: [{ destination: "Tokens.swift", format: "ios-swift/class.swift" }],
},
android: {
transformGroup: "android",
buildPath: "build/android/",
files: [{ destination: "tokens.xml", format: "android/resources" }],
},
},
});
**선택 B를 써야 할 때:**
- *(TODO)*
await sd.buildAllPlatforms();
```
**기본값:**
> *(TODO)*
### Custom transform (px → rem)
```typescript
import StyleDictionary from "style-dictionary";
## ❌ 안티패턴 (Anti-Patterns)
StyleDictionary.registerTransform({
name: "size/pxToRem",
type: "value",
filter: (t) => t.$type === "dimension" && String(t.$value).endsWith("px"),
transform: (t) => `${parseFloat(t.$value) / 16}rem`,
});
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Custom format (Tailwind theme extension)
```typescript
StyleDictionary.registerFormat({
name: "tailwind/theme",
format: ({ dictionary }) => {
const colors: Record<string, any> = {};
for (const t of dictionary.allTokens) {
if (t.$type !== "color") continue;
const path = t.path.join(".");
colors[path] = t.$value;
}
return `module.exports = ${JSON.stringify({ theme: { extend: { colors } } }, null, 2)};`;
},
});
```
### Theme variants (light/dark)
```typescript
// tokens/themes/light.json — refs color/blue/500
// tokens/themes/dark.json — overrides
const themes = ["light", "dark"];
for (const theme of themes) {
const sd = new StyleDictionary({
source: ["tokens/base/**/*.json", `tokens/themes/${theme}.json`],
platforms: {
css: {
transformGroup: "css",
buildPath: "build/css/",
files: [{
destination: `${theme}.css`,
format: "css/variables",
options: { selector: `[data-theme=${theme}]` },
}],
},
},
});
await sd.buildAllPlatforms();
}
```
### CI/CD pipeline (GitHub Actions)
```yaml
# .github/workflows/tokens.yml
name: Build Tokens
on:
push:
branches: [main]
paths: ["tokens/**", "config.ts"]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm tsx config.ts
- name: Commit built tokens
run: |
git config user.name "tokens-bot"
git config user.email "bot@example.com"
git add build/
git diff --cached --quiet || git commit -m "chore(tokens): rebuild [skip ci]"
git push
```
### Figma → Tokens Studio → SD
```bash
# tokens-studio plugin pushes to GitHub:
# tokens.json (single file)
# SD config consumes via custom parser
npx @tokens-studio/sd-transforms init
```
```typescript
import StyleDictionary from "style-dictionary";
import { register } from "@tokens-studio/sd-transforms";
register(StyleDictionary, { excludeParentKeys: true });
const sd = new StyleDictionary({
source: ["tokens.json"],
preprocessors: ["tokens-studio"],
platforms: { css: { /* ... */ } },
});
```
### Validation step
```typescript
// scripts/validate-tokens.ts
import { readFileSync } from "node:fs";
import { z } from "zod";
const TokenSchema = z.object({
$value: z.union([z.string(), z.number()]),
$type: z.enum(["color", "dimension", "fontFamily", "fontWeight", "duration"]),
});
function walk(obj: any, path: string[] = []) {
if ("$value" in obj) {
TokenSchema.parse(obj);
return;
}
for (const [k, v] of Object.entries(obj)) walk(v, [...path, k]);
}
walk(JSON.parse(readFileSync("tokens.json", "utf-8")));
console.log("매 tokens valid");
```
### Storybook integration
```typescript
// .storybook/preview.ts
import "../build/css/light.css";
import "../build/css/dark.css";
export const globalTypes = {
theme: {
name: "Theme",
defaultValue: "light",
toolbar: { items: ["light", "dark"] },
},
};
export const decorators = [
(Story, ctx) => {
document.documentElement.dataset.theme = ctx.globals.theme;
return Story();
},
];
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Web only, simple | CSS vars + Tailwind theme |
| Web + iOS + Android | **Style Dictionary** |
| Figma 동기화 필수 | Tokens Studio + SD |
| 1-person project | 매 overkill — CSS vars 직접 |
| Theme variants | per-theme builds + selector |
**기본값**: Style Dictionary v4 + DTCG JSON + GitHub Actions + multi-platform output. Figma 동기화면 Tokens Studio 추가.
## 🔗 Graph
- 부모: [[Design Tokens]] · [[Design System]] · [[Build Pipelines]]
- 변형: [[Theo]] · [[Tokens Studio]] · [[Specify]]
- 응용: [[Multi-Platform Theming]] · [[Storybook Theming]]
- Adjacent: [[Figma Variables]] · [[DTCG]] · [[CSS Variables]] · [[Tailwind Theme]]
## 🤖 LLM 활용
**언제**: design system bootstrap, multi-platform theming, Figma → code pipeline.
**언제 X**: 매 single-file CSS vars 면 충분한 작은 site. Component-only library without theming.
## ❌ 안티패턴
- **Hard-coded colors**: 매 token 우회 → consistency 무너짐.
- **No reference layer**: 매 component token 이 직접 hex → theme 변경 어려움.
- **Manual sync from Figma**: 매 design drift. 매 Tokens Studio + plugin.
- **No CI build**: 매 local 만 build → mismatched committed output.
- **Token explosion**: 매 100s of brand-specific tokens 양산. Hierarchical reference 사용.
## 🧪 검증 / 중복
- Verified (style-dictionary v4 docs, DTCG spec draft, 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Style Dictionary pipelines canonical full content |