如何使用Style Dictionary将设计Token转换为指定格式SCSS属性
实现方法
不需要自定义输出format,通过Style Dictionary的预处理器(Preprocessor)在token解析前重构结构即可,全程不影响你现有配置的其他token生成逻辑。
核心逻辑
针对所有type: "typography"的复合token,把原本嵌套在value字段下的各字体属性抬升到token根级,每个属性单独包装为{ value: 属性值 }的标准token结构,同时保留根级的type字段,和你要求的输出结构完全匹配。
具体实现
- 在初始化Style Dictionary实例前,注册自定义预处理器:
const StyleDictionary = require("style-dictionary"); // 注册typography结构转换预处理器 StyleDictionary.registerPreprocessor({ name: 'restructure-typography-tokens', preprocessor: (tokenTree) => { const traverse = (node) => { Object.keys(node).forEach(key => { const current = node[key]; // 命中符合特征的typography类型token if ( current?.type === 'typography' && typeof current.value === 'object' && !Array.isArray(current.value) ) { const originValue = current.value; // 删除原嵌套value字段 delete current.value; // 逐个重构属性结构 Object.entries(originValue).forEach(([propKey, propVal]) => { current[propKey] = { value: propVal }; }); } // 递归处理深层嵌套节点 if (typeof current === 'object' && current !== null && !('value' in current)) { traverse(current); } }) return node; } return traverse(tokenTree); } })
- 修改原有配置,在配置根节点启用预处理器,其余所有配置(包括各个scss输出文件的规则、transformGroup)完全不需要改动:
const sd = StyleDictionary.extend({ source: ["./tokens.json"], // 启用刚才注册的预处理器 preprocessors: ['restructure-typography-tokens'], platforms: { scss: { transformGroup: "scss", buildPath: "src/tokens/", files: [ { destination: "_colors.scss", format: "scss/variables", filter: { type: "color" }, }, { destination: "_shadows.scss", format: "scss/variables", filter: { type: "boxShadow" }, }, { destination: "_fontFamilies.scss", format: "scss/variables", filter: { type: "fontFamilies" }, }, { destination: "_lineHeights.scss", format: "scss/variables", filter: { type: "lineHeights" }, }, { destination: "_fontWeights.scss", format: "scss/variables", filter: { type: "fontWeights" }, }, { destination: "_fontSizes.scss", format: "scss/variables", filter: { type: "fontSizes" }, }, { destination: "_letterSpacing.scss", format: "scss/variables", filter: { type: "letterSpacing" }, }, { destination: "_paragraphSpacing.scss", format: "scss/variables", filter: { type: "paragraphSpacing" }, }, { destination: "_typography.scss", format: "scss/variables", filter: { type: "typography" }, }, { destination: "_textCase.scss", format: "scss/variables", filter: { type: "textCase" }, }, { destination: "_textDecoration.scss", format: "scss/variables", filter: { type: "textDecoration" }, }, ], }, }, }); sd.buildAllPlatforms();
注意事项
- 预处理器执行时机早于所有内置transform、token引用解析、format输出流程,原token里的
{fontFamilies.inter.value}这类跨token引用会被正常解析,不会失效 - 该逻辑仅对
typography类型token生效,其他类型token的解析、输出完全不受影响 - 如果后续需要处理其他复合类型token(比如阴影、组合样式token),只需要在预处理器的判断条件里新增对应type,按相同规则重构结构即可
内容的提问来源于stack exchange,提问作者U. Watt
相关产品推荐
相关产品推荐

