You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Style Dictionary配置文件输出Typography Tokens为SCSS变量

问题排查与解决:Style Dictionary 生成Typography SCSS变量显示[object object]

问题根源

你遇到的[object object]是因为:

  1. 默认的scss/variables格式仅能处理字符串/数值类型的令牌值,遇到对象类型时会直接调用toString(),结果就是[object object]
  2. 你配置的自定义typography transform存在字段映射错误(fontSize对应fontsize,大小写不匹配),导致该transform未生效,对象值未被转换
  3. 令牌中存在大量空字符串的字段(如fontWeight: ""),即使transform生效也会生成无效的CSS声明

解决方案

方案1:将Typography对象转换为CSS字体简写

注册自定义transform,过滤空值并生成合法的CSS字体声明:

const StyleDictionary = require('style-dictionary');

// 自定义transform:处理typography令牌,生成CSS字体简写
StyleDictionary.registerTransform({
  name: 'typography/css-shorthand',
  type: 'value',
  matcher: token => token.type === 'typography',
  transformer: token => {
    const { fontWeight, fontSize, lineHeight } = token.value;
    const parts = [];
    // 过滤空值,按CSS字体简写顺序拼接
    if (fontWeight) parts.push(fontWeight);
    if (fontSize) {
      const sizePart = lineHeight ? `${fontSize}/${lineHeight}` : fontSize;
      parts.push(sizePart);
    }
    return parts.join(' ');
  }
});

module.exports = {
  source: [`tokens/*.json`],
  transforms: [
    'attribute/cti',
    'name/cti/kebab',
    'typography/css-shorthand' // 启用自定义transform
  ],
  platforms: {
    scss: {
      buildPath: `style/`,
      files: [{
        destination: `_variables.scss`,
        format: `scss/variables`
      }]
    }
  }
};

同时清理令牌中的空字符串字段,比如将:

"btn-dftypography": {
  "value": {
    "fontWeight": "",
    "fontSize": "1.8rem",
    "lineHeight": ""
  },
  "type": "typography"
}

修改为:

"btn-dftypography": {
  "value": {
    "fontSize": "1.8rem"
  },
  "type": "typography"
}

方案2:将Typography对象转换为SCSS Map

如果需要保留所有字体属性(方便在SCSS中单独调用),可以注册自定义格式生成SCSS Map:

const StyleDictionary = require('style-dictionary');

// 自定义格式:区分处理typography和普通令牌
StyleDictionary.registerFormat({
  name: 'scss/custom-variables',
  formatter: ({ dictionary }) => {
    return dictionary.allTokens.map(token => {
      if (token.type === 'typography') {
        // 过滤空值,生成SCSS Map
        const mapEntries = Object.entries(token.value)
          .filter(([_, val]) => val)
          .map(([key, val]) => `  "${key}": ${val}`)
          .join(',\n');
        return `$${token.name}: (\n${mapEntries}\n);`;
      } else {
        // 普通令牌保持原有格式
        return `$${token.name}: ${token.value};`;
      }
    }).join('\n');
  }
});

module.exports = {
  source: [`tokens/*.json`],
  transforms: [
    'attribute/cti',
    'name/cti/kebab'
  ],
  platforms: {
    scss: {
      buildPath: `style/`,
      files: [{
        destination: `_variables.scss`,
        format: `scss/custom-variables` // 使用自定义格式
      }]
    }
  }
};

生成的Typography变量会是这样的SCSS Map:

$btn-dftypography: (
  "fontSize": 1.8rem
);

内容的提问来源于stack exchange,提问作者Benjamin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:05:26