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

StyleDictionary v3迁移v4后,ts/resolveMath转换无法找到

StyleDictionary v4迁移:解决ts/resolveMath未知转换问题

问题原因

StyleDictionary v4版本移除了ts/resolveMath这个内置转换——该转换在v3中默认可用,但v4不再将其纳入内置转换列表,因此配置中直接引用时会触发“未知转换”的报错。

解决方案

方案1:自定义转换替代原有功能

手动实现一个与ts/resolveMath功能一致的自定义转换,注册后替换配置中的引用:

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

// 注册自定义resolveMath转换
StyleDictionary.registerTransform({
  name: 'my/resolveMath',
  type: 'value',
  matcher: (token) => {
    // 匹配包含数学运算的字符串类型token值
    return typeof token.value === 'string' && /[+\-*/()]/.test(token.value);
  },
  transformer: (token) => {
    // 计算数学表达式(注意:仅当token来源可信时使用eval,避免安全风险)
    return eval(token.value);
  }
});

const sd = new StyleDictionary({
  platforms: {
    js: {
      transforms: [
        "attribute/cti",
        "name/pascal",
        "color/hex",
        "size/rem",
        // 替换为自定义的转换
        "my/resolveMath",
        "my/fontWeight/number",
      ],
      buildPath: "dist/",
      files: [
        {
          destination: "tokens.ts",
          format: "javascript/object",
        },
      ],
    },
  },
});

方案2:预计算token值

直接在token源文件中将需要数学运算的结果计算好,避免在转换阶段处理:

  • 原token示例:{ "size": { "large": { "value": "16px * 2" } } }
  • 修改后:{ "size": { "large": { "value": "32px" } } }

注意事项

StyleDictionary v4对内置转换进行了精简,移除了部分场景化的转换功能,推荐优先采用预计算token值的方式;若必须在转换阶段处理逻辑,再通过自定义转换实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:27:10