如何用Style Dictionary将JSON格式设计令牌转换为CSS变量?
使用Amazon Style Dictionary将设计令牌转成指定格式CSS变量
问题背景
现有包含排版与颜色定义的设计令牌JSON,需要转换为指定格式的CSS变量:
设计令牌示例
{ "semantic": { "typography": { "text": { "xl": { "default": { "value": { "fontFamily": "Roboto", "fontWeight": "400", "lineHeight": "21", "fontSize": "12", "letterSpacing": "14" }, "type": "typography" } } } } }, "color": { "orange": { "100": { "value": "#FFEBD8", "type": "color" }, "200": { "value": "#ffb570", "type": "color" } } } }
期望输出的CSS变量
:root { --fontFamily-xl: "Roboto"; --fontWeight-xl: 400; --lineHeight-xl: 21; --fontSize-xl: 12; --letterSpacing-xl: 14; --color-orange-100: #FFEBD8; --color-orange-200: #ffb570; }
解决方案
默认的Style Dictionary格式无法处理排版令牌的嵌套属性,需要自定义格式器来拆分属性生成目标变量,步骤如下:
1. 创建Style Dictionary配置文件
新建style-dictionary.config.js,内容如下:
const StyleDictionary = require('style-dictionary'); // 自定义格式器:生成符合要求的CSS变量 StyleDictionary.registerFormat({ name: 'custom/css-variables', formatter: ({ dictionary }) => { let cssContent = ':root {\n'; // 处理颜色令牌:按路径拼接变量名 dictionary.allTokens .filter(token => token.type === 'color') .forEach(token => { const varName = `--${token.path.join('-')}`; cssContent += ` ${varName}: ${token.value};\n`; }); // 处理排版令牌:拆解嵌套属性为单独变量 dictionary.allTokens .filter(token => token.type === 'typography') .forEach(token => { // 提取排版尺寸标识(如xl) const sizeKey = token.path.at(-2); Object.entries(token.value).forEach(([prop, value]) => { const varName = `--${prop}-${sizeKey}`; // 字体族需要添加引号包裹 const formattedValue = prop === 'fontFamily' ? `"${value}"` : value; cssContent += ` ${varName}: ${formattedValue};\n`; }); }); cssContent += '}'; return cssContent; } }); module.exports = { // 指定设计令牌文件路径 source: ['tokens/**/*.json'], platforms: { css: { buildPath: 'build/css/', // 输出目录 files: [ { destination: '_variables.css', // 输出文件名 format: 'custom/css-variables' // 使用自定义格式器 } ] } } };
2. 执行转换命令
先安装依赖:
npm install style-dictionary --save-dev
然后运行转换:
npx style-dictionary build
3. 验证结果
执行完成后,build/css/_variables.css文件内容将与期望格式完全一致。
内容的提问来源于stack exchange,提问作者Tchbell
相关产品推荐
相关产品推荐

