用 Style Dictionary 把 Figma Token 转为 Storybook 可用变量

解读

在国内中大型前端团队里,设计系统(Design System)往往由 Figma 设计 Token 驱动,而研发侧又依赖 Storybook 做组件独立开发与文档沉淀。面试官抛出此题,核心想验证三件事:

  1. 你是否理解 Token → 代码变量 → Storybook 样式 的完整链路;
  2. 能否用 Style Dictionary 把 Figma 导出的 JSON 转换成 Web 可用、Tree-shaking 友好、主题可切换 的样式文件;
  3. 是否具备 CI/CD 自动化 思维,让设计变更一键同步到 Storybook,而不是人肉拷贝。

知识点

  1. Figma Token 插件(Tokens Studio for Figma)

    • 支持导出 themes.json、themes.json、metadata.json、tokens.json 三套文件,内含 global、semantic、component 三层 Token。
    • 国内网络需走 Figma 国内代理镜像 或 内网 Git 仓库 做中转,避免拉取失败。
  2. Style Dictionary 核心配置

    • transforms:内置 attribute/cti、color/css、size/rem 等,可自定义 name/cti/camel 生成小驼峰变量名,兼容 JS/TS。
    • formats:css/variables、scss/variables、javascript/es6、typescript/module-declarations 四选一;Storybook 里 CSS 变量 最通用,可配合 prefers-color-scheme 做暗色模式。
    • filters:用 attributes.category === 'color' 把颜色 Token 单独抽离,生成 colors.css,避免冗余。
  3. Storybook 集成

    • 在 .storybook/preview-head.html 里用 <link> 注入 variables.css;
    • 通过 addon-designs 把 Figma 节点 URL 绑定到 story,实现 Token 变更后,Storybook Docs 自动 diff;
    • 用 @storybook/addon-toolbars 注册全局主题切换器,动态切换 data-theme="light|dark",CSS 变量自动响应。
  4. 自动化脚本(国内 GitLab CI 场景)

    • 阶段一:figma-tokens-sync job,拉取最新 Token JSON,校验是否符合 中文命名规范(如不允许出现中文空格);
    • 阶段二:style-dictionary-build job,执行 sd build --config ./sd.config.js,产物推到 packages/theme/dist;
    • 阶段三:chromatic job,把 Storybook 发布到 内网 Chromatic 镜像,飞书群机器人提醒设计同学验收。

答案

  1. Figma 侧导出 在 Tokens Studio 里点击 “Sync to GitHub”,选择 json 格式,目录结构如下:

    tokens/
    ├── $themes.json
    ├── global.json      // 原始值
    └── semantic.json    // 引用 global 的别名
    
  2. Style Dictionary 配置(sd.config.js)

    const StyleDictionary = require('style-dictionary');
    const basePxFontSize = 16; // 国内常见 16px 基准
    
    // 自定义 transform:把 1px 的边框 token 转成 1 而不是 1rem
    StyleDictionary.registerTransform({
      name: 'size/border',
      type: 'value',
      matcher: token => token.attributes.category === 'border' && token.attributes.type === 'width',
      transformer: token => `${token.value}px`
    });
    
    module.exports = {
      source: ['tokens/**/*.json'],
      platforms: {
        cssVariables: {
          transformGroup: 'css',
          transforms: ['attribute/cti', 'name/cti/kebab', 'color/css', 'size/rem', 'size/border'],
          buildPath: 'dist/css/',
          files: [{
            destination: 'variables.css',
            format: 'css/variables',
            options: {
              outputReferences: true, // 保留 var(--xx) 引用关系,便于调试
              selector: ':root'
            }
          }]
        },
        jsModule: {
          transformGroup: 'js',
          transforms: ['attribute/cti', 'name/cti/camel'],
          buildPath: 'dist/js/',
          files: [{
            destination: 'tokens.js',
            format: 'javascript/es6'
          }]
        }
      }
    };
    
  3. npm scripts

    "scripts": {
      "tokens": "style-dictionary build",
      "storybook": "start-storybook -p 6006",
      "build-storybook": "npm run tokens && build-storybook"
    }
    
  4. Storybook 消费

    • 在 .storybook/preview.js 里引入 dist/css/variables.css;
    • 用 addon-toolbars 提供主题切换:
    export const globalTypes = {
      theme: {
        name: '主题',
        description: '全局主题切换',
        defaultValue: 'light',
        toolbar: {
          items: ['light', 'dark'],
          showName: true,
          dynamicTitle: true
        }
      }
    };
    
    const withThemeProvider = (Story, context) => {
      document.documentElement.setAttribute('data-theme', context.globals.theme);
      return Story();
    };
    export const decorators = [withThemeProvider];
    
  5. 暗色模式 CSS 变量示例(自动产出)

    :root {
      --color-bg-default: #ffffff;
      --color-text-primary: #1f1f1f;
    }
    [data-theme="dark"] {
      --color-bg-default: #1f1f1f;
      --color-text-primary: #ffffff;
    }
    
  6. CI 一键同步(GitLab 国内镜像)

    figma-sync:
      stage: tokens
      image: node:18-alpine
      script:
        - npm ci
        - npm run tokens
        - npm run build-storybook
      artifacts:
        paths:
          - dist/
          - storybook-static/
      only:
        - figma-tokens/*  # 仅当设计分支推送时触发
    

至此,设计同学在 Figma 里改一个颜色值,10 分钟内 即可在 内网 Storybook 看到效果,研发无需手工复制粘贴。

拓展思考

  1. 多品牌主题 国内集团常有 主站、金融、电商 三套品牌色,可在 Style Dictionary 里用 brand 维度 做平台区分:

    "color": {
      "primary": { "value": "{color.brand.alipay.blue.6}" }
    }
    

    通过 file.options.selector = "[data-brand='alipay']" 生成三套独立 CSS,Storybook 工具栏再增加 品牌切换器,实现 一次开发,三套皮肤。

  2. Token 回写 研发在 Storybook 里通过 addon-controls 微调变量后,可把结果 反向 PR 到 GitLab,触发 Style Dictionary 的 reverse-dictionary 插件,自动生成 JSON 并回提 Figma,实现 双向绑定,把国内常见的 “设计改→研发追” 变成 闭环协作。

  3. 性能优化 国内低端安卓机占比高,CSS 变量过多会掉帧。可用 postcss-custom-properties 在 Storybook 生产包做 静态替换,只保留 运行时切换所需的变量,其余编译为静态值,减少 60% 动态变量,兼顾可配置与性能。