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大挑战
- Token分层混乱:全局/语义/组件三层边界不清,引用链过长
- 主题切换性能:运行时切换主题导致重绘闪烁
- 多品牌扩展:品牌间Token差异大,继承关系复杂
- 构建输出:多平台(CSS/JS/Swift/Kotlin)输出格式各异
- 设计协作:设计师用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变量优先级和作用域 |
进阶优化
- Token Studio集成:Figma插件实现设计与代码Token双向同步
- Token版本管理:语义化版本号+变更日志自动生成
- A/B测试Token:运行时动态切换Token集进行视觉A/B测试
- Token Lint:ESLint插件检测代码中的硬编码设计值
- Token文档站:自动生成Token可视化文档
对比分析
| 维度 | CSS变量 | Design Token | Tailwind Config | CSS-in-JS Theme |
|---|---|---|---|---|
| 平台支持 | Web only | Web/iOS/Android | Web only | Web only |
| 类型安全 | ❌ | ✅ | ✅ | ✅ |
| 主题切换 | ✅ | ✅ | ✅ | ✅ |
| 多品牌 | 手动 | 原生支持 | 配置切换 | 配置切换 |
| 设计协作 | ❌ | ✅ Figma同步 | ❌ | ❌ |
| 构建输出 | CSS | CSS/JS/Swift/Kotlin | CSS/JS | JS |
总结:Design Token系统是设计系统从"组件库"进化为"设计语言"的关键基础设施。三层Token架构(全局→语义→组件)配合Style Dictionary多平台输出,实现了设计决策的单一数据源。2026年W3C DTCG规范的成熟将推动Token标准化,多品牌和运行时动态Token成为企业级设计系统的标配。
在线工具推荐
- JSON格式化:/zh-CN/json/format
- Hash计算:/zh-CN/encode/hash
- cURL转代码:/zh-CN/dev/curl-to-code
本站提供浏览器本地工具,免注册即可试用 →
#Design Token#设计系统#主题切换#CSS变量#2026#前端工程