如何基于 Style Dictionary 从 Figma Token 生成 Angular Material 主题?

解读

这道题在国内一线/二线大厂的 Angular 岗位面试中出现频率极高,考察点不是“会不会用 Material”,而是“能否把设计系统真正落地到 Angular 工程”。
面试官想确认三件事:

  1. 你熟悉 Figma Token 的 JSON 结构(颜色、字体、阴影、间距、动效等)并能与开发对齐命名规范;
  2. 你掌握 Style Dictionary 的转码管线(transform → format → output),能写自定义 transform 把设计 token 转成 Angular 可消费的 Sass 变量、CSS 变量或 TypeScript 对象;
  3. 你理解 Angular Material 主题系统(@angular/material/theming 提供的 define-palette、define-light-theme、-theme mixin 等),能把转码后的 token 注入到 Material 的调色板、版式、密度、圆角、高程等维度,实现“一键换肤”与“多品牌主题”。
    回答时务必给出 可落地的 CLI 级方案,并说明如何与 CI/CD 结合,体现工程化思维。

知识点

  • Figma Token 插件(Tokens Studio for Figma) 导出的标准格式:metadata、metadata、themes、global、light、dark 等层级
  • Style Dictionary 核心概念:transform(值转换)、format(文件格式)、filter(筛选)、fileHeader、platform、build 脚本
  • Angular Material 主题架构:
    – 调色板(palette)由 50-900 主色 + A100-A700 强调色 + contrast 对比色构成
    – 主题(theme)= 调色板 + 版式(typography)+ 密度(density)+ 圆角(shape)+ 高程(elevation)
    – 使用 mat.define-light-theme / mat.define-dark-theme 生成 $theme 对象,再通过 @include mat.all-component-themes($theme) 注入组件
  • Sass:map 与 map.merge 用于动态拼接 token 生成的 map
  • CSS Variables 降级方案:在 :root 中输出变量,供非 Material 组件消费
  • CI 集成:npm script → husky → lint-staged → style-dictionary build → Angular CLI 自动 reload
  • 多品牌/多租户场景:利用 Style Dictionary 的 brand/ 子目录 + 环境变量 BRAND=xxx 生成差异化主题文件,Angular 在构建时用 fileReplacements 替换 src/assets/theme/_brand.scss

答案

  1. 命名对齐
    与设计师约定 BEM-like 命名:color.primary.500、font.weight.semibold、shadow.card.light。Figma Token 插件勾选 “Use dollar prefixes” 关闭,避免 Sass 语法冲突。

  2. 导出 Token
    在 Figma 中执行 Tokens Studio → Export → JSON (nested),得到 tokens.json,存到仓库 design-tokens/ 目录。

  3. 初始化 Style Dictionary

    npm i -D style-dictionary ts-node @types/node
    npx style-dictionary init
    

    删除默认的 config.json,新建 sd.config.ts:

    import StyleDictionary from 'style-dictionary';
    import { materialTransformGroup } from './scripts/sd-material-transform';
    
    export default {
      source: ['design-tokens/**/*.json'],
      platforms: {
        // 1. 生成 Material 调色板 Sass map
        materialPalette: {
          transformGroup: 'materialTransformGroup',
          buildPath: 'src/assets/theme/',
          files: [
            {
              destination: '_palette.scss',
              format: 'scss/material-palette',
              filter: token => token.attributes.category === 'color'
            }
          ]
        },
        // 2. 生成 CSS 变量(供运行时切换)
        cssVariables: {
          transformGroup: 'css',
          buildPath: 'src/assets/theme/',
          files: [
            {
              destination: 'variables.css',
              format: 'css/variables',
              filter: token => token.attributes.category === 'color'
            }
          ]
        }
      }
    };
    
  4. 自定义 transform & format
    在 scripts/sd-material-transform.ts 中注册:

    import StyleDictionary from 'style-dictionary';
    
    StyleDictionary.registerTransform({
      name: 'color/material-500',
      type: 'value',
      matcher: token => token.attributes.category === 'color' && token.attributes.type === 'primary',
      transformer: token => token.value.replace('#', '0x') // Material 需要 0x 前缀
    });
    
    StyleDictionary.registerFormat({
      name: 'scss/material-palette',
      formatter: ({ dictionary }) => {
        const lines = ['$my-palette: ('];
        dictionary.allTokens
          .filter(t => t.attributes.category === 'color')
          .forEach(t => {
            const key = t.attributes.type + '-' + t.attributes.item; // primary-500
            lines.push(`  ${key}: ${t.value},`);
          });
        lines.push(');', '@function my-palette() { @return $my-palette; }');
        return lines.join('\n');
      }
    });
    
  5. 生成 Angular Material 主题
    在 src/assets/theme/_material-theme.scss 中:

    @use '@angular/material' as mat;
    @import 'palette';
    
    $primary-palette: mat.define-palette(my-palette(), 500, 300, 700);
    $accent-palette:  mat.define-palette(my-palette(), A200, A100, A400);
    $warn-palette:    mat.define-palette(mat.$red-palette); // 可同样替换
    
    $light-theme: mat.define-light-theme((
      color: (
        primary: $primary-palette,
        accent:  $accent-palette,
        warn:    $warn-palette
      ),
      typography: mat.define-typography-config(
        $font-family: var(--font-family-base, 'Roboto'),
        $headline-1: mat.define-typography-level(2.125rem, 2.5rem, 300),
        // …其余版式 token 同样映射
      ),
      density: -1 // 对应 token 中 size.scale
    ));
    
    @include mat.all-component-themes($light-theme);
    
  6. 运行时切换深色模式
    利用 CSS Variables 版本,在 AppComponent 中监听用户偏好:

    @HostBinding('class') themeClass = 'light';
    toggleDark() {
      this.themeClass = this.themeClass === 'light' ? 'dark' : 'light';
      document.body.classList.toggle('dark');
    }
    

    在 variables.css 中:

    :root { --color-primary-500: #1976d2; }
    body.dark { --color-primary-500: #90caf9; }
    
  7. 脚本与 CI
    package.json:

    "scripts": {
      "tokens": "style-dictionary build --config ./sd.config.ts",
      "start": "npm run tokens && ng serve",
      "build": "npm run tokens && ng build"
    }
    

    GitHub Actions 中增加一步:

    - run: npm run tokens
    - run: npm run build -- --configuration=production
    

    确保设计师 MR 后,token 自动生效,无需人工拷贝。

  8. 验证
    在 Storybook 或 app.component.html 中放 <mat-button>、<mat-card>,切换品牌/深浅色,确认色值与 Figma 完全一致。使用 Chromatic 做视觉回归,防止 token 回归错误。

拓展思考

  1. 多品牌动态注入
    把 BRAND=bankA|bankB 作为环境变量,CI 中执行 style-dictionary build --brand=${BRAND},生成 bankA-theme.scss、bankB-theme.scss,Angular 用 APP_INITIALIZER 动态加载对应 CSS,实现 “一套代码,多品牌上架”。

  2. Token 分级与权限
    在大厂设计系统里,基础 token(global.json) 由设计系统团队锁定,语义 token(semantic.json) 由业务线维护。Style Dictionary 的 filter 可拆分产物,配合 lerna/monorepo 做分层发包,避免业务线随意篡改基础色。

  3. 性能优化
    对深色模式无需重新加载整包,借助 CSS Variables + Material 的 color CSS API(mat.get-color-from-palette)把色值抽成变量,切换时仅替换变量,无闪烁、无重新打包。

  4. 设计-开发闭环
    用 Figma Webhook 监听 Token 文件变更,触发 GitHub Action 自动提 PR,PR 标题带 “design-token” 标签,机器人自动跑视觉回归,通过后合并,实现 “今天设计师改色,明天线上生效” 的 DevOps 体验。

  5. 无障碍合规
    在 transform 阶段增加 WCAG 对比度检测:
    import { relativeLuminance, contrast } from 'wcag-color';
    若 contrast(token.value, '#ffffff') < 4.5,则抛出错误,阻断构建,确保国内金融、政府项目过 工信部无障碍评测。

掌握以上思路,你不仅回答了“怎么生成”,更展示了“如何落地、如何规模化、如何保障质量”,在国内面试中可直接对标 阿里 Fusion、腾讯 TDesign、字节 Arco 的 Design Token 工程化实践,轻松拿到高分。