Design Token系統實戰:5個模式構建可擴展主題與多品牌架構

前端工程

Design Token:設計系統的原子級基礎設施

設計系統最大的痛點不是元件不夠多,而是主題切換靠覆蓋、品牌擴展靠複製、暗色模式靠補丁。Design Token將顏色、間距、字型等設計決策抽象為平臺無關的鍵值對,實現「一次定義、多端消費」。2026年,W3C Design Token規範進入Candidate Recommendation,Style Dictionary 4.0+支援多平臺輸出,Design Token已成為設計系統的標準基礎設施。

本文將從5種核心模式出發,帶你完成Token分層→主題切換→多品牌→建構流水線→執行時動態的全鏈路實戰。


核心概念

概念 說明
Design Token 設計決策的原子級表示,鍵值對形式
Global Token 全域原始值,如blue-500: #3b82f6
Alias Token 語義化別名,如primary: {blue-500}
Component Token 元件級Token,如button-primary-bg: {primary}
Theme 一組Token值的集合,如亮色/暗色主題
Multi-Brand 同一設計系統支援多個品牌的Token集
Style Dictionary Token編譯工具,輸出多平臺格式
W3C DTCG Design Token Community Group規範

問題分析:Design Token系統的5大挑戰

  1. Token分層混亂:全域/語義/元件三層邊界不清,參照鏈過長
  2. 主題切換效能:執行時切換主題導致重繪閃爍
  3. 多品牌擴展:品牌間Token差異大,繼承關係複雜
  4. 建構輸出:多平臺(CSS/JS/Swift/Kotlin)輸出格式各異
  5. 設計協作:設計師用Figma、開發者用程式碼,Token同步困難

分步實操:5種Design Token模式

模式1:Token三層分層架構

// tokens/global/color.json
{
  "color": {
    "blue": {
      "100": { "value": "#dbeafe", "type": "color" },
      "500": { "value": "#3b82f6", "type": "color" },
      "900": { "value": "#1e3a8a", "type": "color" }
    },
    "gray": {
      "50": { "value": "#f9fafb", "type": "color" },
      "900": { "value": "#111827", "type": "color" }
    },
    "red": {
      "500": { "value": "#ef4444", "type": "color" }
    },
    "green": {
      "500": { "value": "#22c55e", "type": "color" }
    }
  }
}
// tokens/semantic/color.json
{
  "color": {
    "primary": { "value": "{color.blue.500}", "type": "color" },
    "primary-hover": { "value": "{color.blue.600}", "type": "color" },
    "background": { "value": "{color.gray.50}", "type": "color" },
    "surface": { "value": "#ffffff", "type": "color" },
    "text": { "value": "{color.gray.900}", "type": "color" },
    "text-secondary": { "value": "{color.gray.500}", "type": "color" },
    "error": { "value": "{color.red.500}", "type": "color" },
    "success": { "value": "{color.green.500}", "type": "color" },
    "border": { "value": "{color.gray.200}", "type": "color" }
  }
}
// tokens/component/button.json
{
  "button": {
    "primary": {
      "bg": { "value": "{color.primary}", "type": "color" },
      "bg-hover": { "value": "{color.primary-hover}", "type": "color" },
      "text": { "value": "#ffffff", "type": "color" },
      "border-radius": { "value": "{radius.md}", "type": "borderRadius" },
      "padding-x": { "value": "{spacing.4}", "type": "spacing" },
      "padding-y": { "value": "{spacing.2}", "type": "spacing" }
    },
    "secondary": {
      "bg": { "value": "{color.surface}", "type": "color" },
      "text": { "value": "{color.primary}", "type": "color" },
      "border": { "value": "{color.border}", "type": "color" }
    }
  }
}

模式2:主題切換(亮色/暗色)

// tokens/semantic/color.dark.json
{
  "color": {
    "primary": { "value": "{color.blue.400}", "type": "color" },
    "background": { "value": "{color.gray.900}", "type": "color" },
    "surface": { "value": "#1f2937", "type": "color" },
    "text": { "value": "{color.gray.50}", "type": "color" },
    "text-secondary": { "value": "{color.gray.400}", "type": "color" },
    "border": { "value": "{color.gray.700}", "type": "color" }
  }
}
/* 建構輸出:tokens.css */
:root {
  --color-primary: #3b82f6;
  --color-background: #f9fafb;
  --color-surface: #ffffff;
  --color-text: #111827;
  --color-border: #e5e7eb;
  --button-primary-bg: var(--color-primary);
  --button-primary-text: #ffffff;
}

[data-theme="dark"] {
  --color-primary: #60a5fa;
  --color-background: #111827;
  --color-surface: #1f2937;
  --color-text: #f9fafb;
  --color-border: #374151;
  --button-primary-bg: var(--color-primary);
}
// 主題切換器
type Theme = 'light' | 'dark' | 'system';

class ThemeManager {
  private mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  private listeners: Set<(theme: Theme) => void> = new Set();

  init() {
    const saved = localStorage.getItem('theme') as Theme | null;
    if (saved && saved !== 'system') {
      this.apply(saved);
    } else {
      this.apply(this.mediaQuery.matches ? 'dark' : 'light');
    }
    this.mediaQuery.addEventListener('change', (e) => {
      if (this.getStored() === 'system') {
        this.apply(e.matches ? 'dark' : 'light');
      }
    });
  }

  setTheme(theme: Theme) {
    localStorage.setItem('theme', theme);
    if (theme === 'system') {
      this.apply(this.mediaQuery.matches ? 'dark' : 'light');
    } else {
      this.apply(theme);
    }
    this.listeners.forEach((fn) => fn(theme));
  }

  private apply(mode: 'light' | 'dark') {
    document.documentElement.setAttribute('data-theme', mode);
  }

  private getStored(): Theme {
    return (localStorage.getItem('theme') as Theme) || 'system';
  }

  onChange(fn: (theme: Theme) => void) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn);
  }
}

模式3:多品牌Token繼承

// brands/brand-a/tokens.json
{
  "color": {
    "primary": { "value": "#3b82f6", "type": "color", "$extensions": { "brand": "A" } },
    "primary-hover": { "value": "#2563eb", "type": "color" }
  },
  "typography": {
    "font-family": { "value": "Inter, sans-serif", "type": "fontFamily" },
    "heading-weight": { "value": "700", "type": "fontWeight" }
  },
  "radius": {
    "base": { "value": "8px", "type": "borderRadius" }
  }
}
// brands/brand-b/tokens.json
{
  "color": {
    "primary": { "value": "#8b5cf6", "type": "color", "$extensions": { "brand": "B" } },
    "primary-hover": { "value": "#7c3aed", "type": "color" }
  },
  "typography": {
    "font-family": { "value": "Poppins, sans-serif", "type": "fontFamily" },
    "heading-weight": { "value": "600", "type": "fontWeight" }
  },
  "radius": {
    "base": { "value": "4px", "type": "borderRadius" }
  }
}
// 品牌切換器
type Brand = 'brand-a' | 'brand-b';

async function switchBrand(brand: Brand) {
  const brandCSS = await fetch(`/tokens/${brand}.css`).then((r) => r.text());
  let style = document.getElementById('brand-tokens') as HTMLStyleElement;
  if (!style) {
    style = document.createElement('style');
    style.id = 'brand-tokens';
    document.head.appendChild(style);
  }
  style.textContent = brandCSS;
  document.documentElement.setAttribute('data-brand', brand);
  localStorage.setItem('brand', brand);
}

模式4:Style Dictionary建構流水線

// style-dictionary.config.mjs
import StyleDictionary from 'style-dictionary';

StyleDictionary.registerTransform({
  name: 'size/pxToRem',
  type: 'value',
  matcher: (token) => token.type === 'spacing' || token.type === 'fontSize',
  transformer: (token) => {
    const base = 16;
    const val = parseFloat(token.value);
    return `${val / base}rem`;
  },
});

StyleDictionary.registerTransformGroup({
  name: 'custom/css',
  transforms: [
    'attribute/cti',
    'name/kebab',
    'time/seconds',
    'size/pxToRem',
    'color/css',
  ],
});

const config = {
  source: ['tokens/**/*.json'],
  platforms: {
    css: {
      transformGroup: 'custom/css',
      buildPath: 'dist/css/',
      files: [
        {
          destination: 'tokens.css',
          format: 'css/variables',
          options: { outputReferences: true },
        },
      ],
    },
    js: {
      transformGroup: 'js',
      buildPath: 'dist/js/',
      files: [
        {
          destination: 'tokens.js',
          format: 'javascript/es6',
        },
        {
          destination: 'tokens.d.ts',
          format: 'typescript/es6-declarations',
        },
      ],
    },
    json: {
      transformGroup: 'json',
      buildPath: 'dist/json/',
      files: [
        {
          destination: 'tokens.json',
          format: 'json',
        },
      ],
    },
    ios: {
      transformGroup: 'ios-swift-separate',
      buildPath: 'dist/ios/',
      files: [
        {
          destination: 'DesignTokens.swift',
          format: 'ios-swift/class.swift',
          className: 'DesignTokens',
        },
      ],
    },
    android: {
      transformGroup: 'android',
      buildPath: 'dist/android/',
      files: [
        {
          destination: 'design_tokens.xml',
          format: 'android/resources',
        },
      ],
    },
  },
};

export default config;
# 建構所有平臺
npx style-dictionary build

# 監聽Token變更
npx style-dictionary build --watch

模式5:執行時動態Token

// runtime-token-engine.ts
interface TokenValue {
  value: string;
  type: string;
  description?: string;
}

class RuntimeTokenEngine {
  private tokens: Map<string, TokenValue> = new Map();
  private subscribers: Map<string, Set<(value: string) => void>> = new Map();

  loadFromCSS() {
    const styles = getComputedStyle(document.documentElement);
    const allVars = Array.from(document.styleSheets)
      .flatMap((sheet) => {
        try {
          return Array.from(sheet.cssRules);
        } catch {
          return [];
        }
      })
      .filter((rule) => rule instanceof CSSStyleRule)
      .flatMap((rule: CSSStyleRule) => {
        const props: string[] = [];
        for (let i = 0; i < rule.style.length; i++) {
          const prop = rule.style[i];
          if (prop.startsWith('--')) {
            props.push(prop);
          }
        }
        return props;
      });

    const uniqueVars = [...new Set(allVars)];
    uniqueVars.forEach((v) => {
      const val = styles.getPropertyValue(v).trim();
      if (val) {
        this.tokens.set(v, { value: val, type: 'unknown' });
      }
    });
  }

  setToken(name: string, value: string) {
    const varName = name.startsWith('--') ? name : `--${name}`;
    document.documentElement.style.setProperty(varName, value);
    this.tokens.set(varName, { value, type: 'unknown' });
    this.notify(varName, value);
  }

  getToken(name: string): string | undefined {
    const varName = name.startsWith('--') ? name : `--${name}`;
    return getComputedStyle(document.documentElement)
      .getPropertyValue(varName)
      .trim();
  }

  subscribe(name: string, callback: (value: string) => void) {
    const varName = name.startsWith('--') ? name : `--${name}`;
    if (!this.subscribers.has(varName)) {
      this.subscribers.set(varName, new Set());
    }
    this.subscribers.get(varName)!.add(callback);
    return () => this.subscribers.get(varName)?.delete(callback);
  }

  private notify(name: string, value: string) {
    this.subscribers.get(name)?.forEach((fn) => fn(value));
  }
}

避坑指南

坑1:Token參照鏈過深

// ❌ 錯誤:5層參照鏈,除錯困難
{
  "btn-bg": { "value": "{button.primary.bg}" },
  "button.primary.bg": { "value": "{color.primary}" },
  "color.primary": { "value": "{blue.500}" }
}

// ✅ 正確:控制在3層以內
{
  "button-primary-bg": { "value": "{color.primary}" },
  "color.primary": { "value": "#3b82f6" }
}

坑2:硬編碼顏色值

/* ❌ 錯誤:硬編碼顏色 */
.card { background: #ffffff; border: 1px solid #e5e7eb; }

/* ✅ 正確:使用Token變數 */
.card { background: var(--color-surface); border: 1px solid var(--color-border); }

坑3:主題切換閃爍

<!-- ❌ 錯誤:JS載入後才設定主題,導致閃爍 -->

<!-- ✅ 正確:內聯指令碼阻塞渲染 -->
<script>
  (function() {
    const theme = localStorage.getItem('theme');
    if (theme === 'dark' || (!theme && matchMedia('(prefers-color-scheme: dark)').matches)) {
      document.documentElement.setAttribute('data-theme', 'dark');
    }
  })();
</script>

坑4:元件Token濫用

// ❌ 錯誤:每個元件屬性都建立Token
{
  "card-padding-top": { "value": "{spacing.4}" },
  "card-padding-right": { "value": "{spacing.4}" },
  "card-padding-bottom": { "value": "{spacing.4}" },
  "card-padding-left": { "value": "{spacing.4}" }
}

// ✅ 正確:複用語義Token
{
  "card-padding": { "value": "{spacing.4}" }
}

坑5:忽略Token型別校驗

// ❌ 錯誤:不校驗Token型別,顏色Token傳了間距值
// ✅ 正確:建構時校驗
StyleDictionary.registerFilter({
  name: 'isValidColor',
  matcher: (token) => {
    if (token.type === 'color') {
      return /^#([0-9a-f]{3}){1,2}$/i.test(token.value) ||
             token.value.startsWith('{');
    }
    return true;
  },
});

報錯排查

序號 報錯資訊 原因 解決方法
1 Reference not found: {color.xxx} Token參照了不存在的鍵 檢查參照路徑拼寫
2 Circular reference detected Token迴圈參照 打破迴圈參照鏈
3 Invalid token value Token值格式不合法 校驗顏色/間距格式
4 CSS variable not applied 選擇器優先級被覆蓋 提高CSS變數選擇器優先級
5 Theme flash on load 主題初始化晚於渲染 內聯阻塞指令碼設定主題
6 Style Dictionary build failed Token檔案格式錯誤 檢查JSON語法和$extensions
7 Token not found in output Token未被source匹配 檢查source glob路徑
8 Platform output mismatch 轉換規則不一致 統一transformGroup設定
9 Figma sync conflict Figma Token與程式碼不一致 使用Token Studio雙向同步
10 Runtime token override fails 執行時覆蓋不生效 檢查CSS變數優先級和作用域

進階最佳化

  1. Token Studio整合:Figma外掛實現設計與程式碼Token雙向同步
  2. Token版本管理:語義化版本號+變更日誌自動生成
  3. A/B測試Token:執行時動態切換Token集進行視覺A/B測試
  4. Token Lint:ESLint外掛檢測程式碼中的硬編碼設計值
  5. Token文件站:自動生成Token視覺化文件

對比分析

維度 CSS變數 Design Token Tailwind Config CSS-in-JS Theme
平臺支援 僅Web Web/iOS/Android 僅Web 僅Web
型別安全
主題切換
多品牌 手動 原生支援 設定切換 設定切換
設計協作 ✅ Figma同步
建構輸出 CSS CSS/JS/Swift/Kotlin CSS/JS JS

總結:Design Token系統是設計系統從「元件庫」進化為「設計語言」的關鍵基礎設施。三層Token架構(全域→語義→元件)配合Style Dictionary多平臺輸出,實現了設計決策的單一資料來源。2026年W3C DTCG規範的成熟將推動Token標準化,多品牌和執行時動態Token成為企業級設計系統的標配。


線上工具推薦

本站提供瀏覽器本地工具,免註冊即可試用 →

#Design Token#设计系统#主题切换#CSS变量#2026#前端工程