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
相关产品推荐
相关产品推荐

