如何设计一个可扩展的 theme.config.ts 文件来管理颜色、字体等主题变量?
解读
国内一线团队普遍把“主题”当成产品级资产,需要同时满足:
- 设计、产品、开发三端协同(Design Token 规范)
- 多品牌、多场景、暗黑模式等动态切换
- 与 Vite 的按需加载、HMR、Tree-Shaking 深度结合
- 后续可接入低代码、可视化配置平台
因此面试官想考察的不只是“写个对象”,而是能否给出一套“可演进、可交付、可维护”的工程化方案,并解释在 Vite 生态里如何落地。
知识点
- Design Token 分层理论(Global / Alias / Component)
- TypeScript 类型体操:const assertion、模板字面量类型、递归 keyof
- CSS Variables 注入与 Vite 插件顺序(transformIndexHtml、configResolved)
- 动态主题切换:vite-plugin-theme、@vitejs/plugin-legacy 兼容
- 灰度发布与实验性开关(feature flag)
- 颜色算法:wcag contrast、oklch 插值、暗黑模式自动反转
- 产物优化:拆包策略、预构建缓存、HTTP2 多路复用
- 团队协作:Style Dictionary、Figma Tokens、npm 私包、changeset 版本管理
答案
以下示例基于 Vite + Vue3 + TypeScript,但同样适用于 React。思路是“三层两协议一插件”:
- 三层:Global Token → Semantic Token → Component Token
- 两协议:
- 命名协议:kebab-case + BEM 后缀,如
--color-primary-default - 版本协议:Semver + changeset,保证主题包向后兼容
- 命名协议:kebab-case + BEM 后缀,如
- 一插件:自定义 vite-plugin-theme 负责把 Token 注入 HTML 与 CSS,并暴露
updateTheme()运行时 API
目录结构
packages/
├─ theme/
│ ├─ tokens/ // 原始 token
│ │ ├─ global.ts
│ │ ├─ semantic.ts
│ │ └─ component.ts
│ ├─ build.ts // Style Dictionary 生成多格式产物
│ ├─ theme.config.ts // 用户侧唯一入口
│ ├─ index.ts // 导出 TS 类型与 runtime
│ └─ package.json
├─ app/
│ ├─ vite.config.ts
│ └─ src/main.ts
核心代码
// packages/theme/tokens/global.ts
export const global = {
color: {
white: '#ffffff',
black: '#000000',
blue: {
50: '#f0f9ff',
500: '#3b82f6',
900: '#172554',
},
},
font: {
sans: 'Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
mono: 'Fira Code, monospace',
},
space: {
1: '4px',
2: '8px',
3: '12px',
},
} as const;
// packages/theme/tokens/semantic.ts
import { global } from './global';
export const semantic = {
light: {
'color-primary': global.color.blue[500],
'color-bg': global.color.white,
'color-text': global.color.black,
},
dark: {
'color-primary': global.color.blue[400],
'color-bg': global.color.black,
'color-text': global.color.white,
},
} as const;
// packages/theme/theme.config.ts
import { global, semantic } from './tokens';
import type { ComponentToken } from './tokens/component';
export interface ThemeConfig {
global: typeof global;
semantic: typeof semantic;
component: ComponentToken;
// 实验性开关
features: {
enableOkLCH: boolean;
darkAutoDetect: boolean;
};
}
export const defineTheme = (config: ThemeConfig) => config;
export default defineTheme({
global,
semantic,
component: {
button: {
'padding-x': global.space[3],
'border-radius': '6px',
},
},
features: {
enableOkLCH: true,
darkAutoDetect: true,
},
});
插件实现(精简)
// packages/theme/vite-plugin-theme.ts
import type { Plugin } from 'vite';
import { parse, stringify } from '@style-dictionary/utils';
export function vitePluginTheme(configPath = 'theme.config.ts'): Plugin {
let config: ThemeConfig;
return {
name: 'vite-plugin-theme',
configResolved() {
// 热更新阶段重新加载
delete require.cache[require.resolve(configPath)];
config = require(configPath).default;
},
transformIndexHtml: {
order: 'pre',
handler(html) {
const cssVars = flattenToken(config.semantic.light); // 默认白天
const style = `<style>:root{${cssVars}}</style>`;
return html.replace('<head>', `<head>${style}`);
},
},
handleHotUpdate({ file, server }) {
if (file.endsWith('theme.config.ts')) {
server.ws.send({ type: 'full-reload' });
}
},
};
function flattenToken(obj: Record<string, any>, prefix = '--'): string {
return Object.entries(obj)
.map(([k, v]) =>
typeof v === 'string' ? `${prefix}${k}:${v};` : flattenToken(v, `${prefix}${k}-`)
)
.join('');
}
}
运行时 API
// packages/theme/runtime.ts
export function updateTheme(mode: 'light' | 'dark') {
const root = document.documentElement;
const tokens = mode === 'dark' ? semantic.dark : semantic.light;
Object.entries(flattenToken(tokens)).forEach(([key, value]) => {
root.style.setProperty(key, value);
});
localStorage.setItem('theme-preference', mode);
}
接入业务
// app/vite.config.ts
import { vitePluginTheme } from '@my-org/theme/vite-plugin-theme';
export default defineConfig({
plugins: [vue(), vitePluginTheme()],
});
// app/src/main.ts
import { updateTheme } from '@my-org/theme/runtime';
updateTheme(localStorage.getItem('theme-preference') || 'light');
可扩展性保证
- 新增品牌:在 semantic.ts 里再建一套 brandB,通过
defineTheme({...})合并即可 - 组件层扩展:在 component 目录下按组件新建文件,使用 TypeScript 模块合并声明
- 颜色算法:在 features.enableOkLCH 开启后,插件自动把 hex 转为 oklch,保证渐变平滑且符合 WCAG
- 灰度发布:在 CI 里读取环境变量
THEME_FLAG=beta,把实验性 token 打入独立 chunk,通过异步import()加载,失败自动回退 - 性能:Style Dictionary 预编译阶段生成
.css、.less、.scss、.json多格式,Vite 预构建缓存命中 100%,HMR 只替换变量不刷新页面
拓展思考
-
如果产品需要“用户自定义主题色”,如何防止 XSS 与颜色注入?
答:在运行时对输入做oklch()正则校验,把结果写入 CSS 变量,禁止直接插入内联样式;同时通过 CSP 限制style-src 'self' 'unsafe-inline'只放行白名单域名。 -
微前端场景下,子应用主题如何与基座保持同步?
答:基座通过@my-org/theme的updateTheme发布自定义事件ThemeChange,子应用监听后调用同一函数;token 包使用 semver 范围依赖,基座锁定大版本,防止子应用漂移。 -
当设计团队用 Figma Tokens 推送更新,如何做到“设计到代码一分钟上线”?
答:在 GitLab CI 里监听 Figma Webhook,自动拉取 JSON,调用 Style Dictionary 生成产物,触发 changeset 版本补丁,合并后自动发布 npm 私包;Vite 项目通过~范围依赖,五分钟内完成 CI 升级与灰度。 -
如果未来需要 SSR(如 Nuxt、SSR React),上述插件是否仍然适用?
答:需要把transformIndexHtml阶段换成generateBundle阶段注入 CSS,并在服务端渲染前根据req.headers.cookie或user-agent预取主题,保证首屏无闪烁;Vite 5 的environmentAPI 已支持 SSR 插件隔离,可直接复用同一套 token 定义。