如何将 Style Dictionary 输出的 JSON 转换为 PostCSS 自定义属性插件可用的格式?

解读

Style Dictionary 负责把设计令牌(tokens)统一输出成多端可用的“常量”,而 PostCSS 插件(如 postcss-custom-properties)只认符合 CSS 自定义属性语法(--key: value;)的 AST 节点。
面试时,面试官真正想确认的是:

  1. 你是否理解 Style Dictionary 的“格式扩展”机制(formats、transforms、filters);
  2. 你是否能把“非 CSS”结构(嵌套对象、数字、引用、模式匹配)扁平化成合法 CSS 变量名;
  3. 你是否能把转换逻辑做成可复用、可发布的 npm 包,并能在 Vite / Webpack 链路里零配置接入;
  4. 你是否考虑到了 Tree-Shaking、产物体积、运行时更新、SSR 等国内工程化痛点。
    一句话:不是“写个脚本”就完事,而是“给团队搭一条可持续交付的设计令牌链路”。

知识点

  1. Style Dictionary 生命周期:clean → transform → format → filter → output;
  2. 自定义 format 的模板引擎(Handlebars / Lodash template / 纯函数);
  3. CSS 自定义属性命名规则:必须以 -- 开头,只能包含字母、数字、-、_,区分大小写;
  4. 嵌套对象扁平化算法(DFS + 路径拼接 + 冲突检测);
  5. 值类型映射:数字→带单位(px / rem)、颜色→rgba / #、引用→var()、渐变→完整字符串;
  6. PostCSS AST 节点类型:rule、decl、comment;
  7. 插件发布规范:main 指向 dist/index.js,types 指向 index.d.ts,files 白名单,peerDependencies 声明 postcss 版本;
  8. 国内私有源(Verdaccio / 阿里 CNPM)发布流程,以及 .npmrc 配置;
  9. 热更新场景:通过 vite-plugin-style-dictionary 监听 tokens/ 目录,增量生成 vars.css,触发 HMR;
  10. 灰度与回滚:在 Qiankun 微前端里,主子应用共享同一份 vars.css,需做 CSS 隔离与版本号戳。

答案

  1. 在 Style Dictionary 项目里新建 src/formats/postcss-custom-properties.js
const { fileHeader } = require('style-dictionary/lib/common/formatHelpers');

function flattenTokens(obj, path = []) {
  const decls = [];
  function walk(cur, p) {
    if (Object(cur) !== cur) {
      // 基本值
      const cssVar = '--' + p.join('-');
      let value = cur;
      // 单位处理
      if (typeof value === 'number') value = value + 'px';
      // 引用处理
      if (typeof value === 'string' && value.startsWith('{')) {
        const refPath = value.slice(1, -1).split('.');
        value = `var(--${refPath.join('-')})`;
      }
      decls.push(`  ${cssVar}: ${value};`);
      return;
    }
    Object.keys(cur).forEach(k => walk(cur[k], [...p, kebabCase(k)]));
  }
  walk(obj, path);
  return decls.join('\n');
}

function kebabCase(str) {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
}

module.exports = ({ dictionary, file }) => {
  return (
    fileHeader({ file }) +
    ':root {\n' +
    flattenTokens(dictionary.properties) +
    '\n}\n'
  );
};
  1. 在 config.json 中注册该格式
{
  "source": ["tokens/**/*.json"],
  "platforms": {
    "css": {
      "transformGroup": "css",
      "buildPath": "dist/css/",
      "files": [{
        "destination": "variables.css",
        "format": "postcss/custom-properties"
      }]
    }
  }
}
  1. 在 PostCSS 插件侧消费
// postcss.config.js
module.exports = {
  plugins: [
    require('postcss-custom-properties')({
      importFrom: ['node_modules/your-design-tokens/dist/css/variables.css'],
      preserve: true
    })
  ]
}
  1. 打包与发布
  • 把步骤 1 的代码抽成 npm 包 postcss-sd-formatter,入口暴露 register 函数,在用户侧只需 require('postcss-sd-formatter').register(sd) 即可挂载格式;
  • 在 package.json 中声明 peerDependencies: { "style-dictionary": ">=3.0.0" },避免重复安装;
  • 提供 TypeScript 声明,方便国内主流 TypeScript 项目(阿里、字节、美团)直接引用;
  • 通过 GitHub Actions 自动发布到 CNPM 私有源,并同步生成变更日志(conventional-changelog)。
  1. 国内工程化加分项
  • 提供 Vite 插件 vite-plugin-sd2postcss,监听 tokens 目录,增量生成 vars.css,并触发 server.ws.send({ type: 'full-reload' }),实现毫秒级热更新;
  • 在 SSR 场景(Next.js)中,把 vars.css 注入到 _document.tsx 的 <style data-token-version="1.2.3"> 标签,避免客户端闪动;
  • 通过 postcss-plugin 内联版本号戳,方便 Sentry 报错时快速定位设计令牌版本。

拓展思考

  1. 如果设计令牌量级达到 10k+,生成的 vars.css 体积 200KB+,如何按需加载?
    思路:利用 Style Dictionary 的 “attribute” 标记,把组件级令牌拆成多文件,再通过 Vite 的 ?inline 与 CSS Module 组合,实现组件懒加载;同时写 PostCSS 插件做变量摇树,把未被 var() 引用的声明删除。

  2. 如何支持“深色模式”与“主题品牌包”?
    思路:在扁平化阶段为每个令牌追加 {color, mode} 维度,生成

:root { --btn-bg: #fff; }
[data-theme="dark"] { --btn-bg: #000; }

并通过 postcss-custom-properties 的 exportTo 把变量表回写到 JSON,供 JS 侧做运行时切换。

  1. 国内低代码平台(阿里宜搭、腾讯微搭)直接拖拽组件时,如何实时同步令牌?
    思路:把上述流程封装成 WebSocket 服务,设计稿改动后推送 diff,平台侧通过 CSSOM 直接更新 document.body.style.setProperty,无需重新打包,实现“设计即发布”。

  2. 面试反向提问:
    “贵公司目前设计令牌到 PostCSS 的链路耗时多久?是否出现过变量名冲突或灰度不一致的问题?”
    体现你对性能、稳定性、业务灰度的深度关注,拉高面试官对你的技术评级。