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

如何在Amazon Style Dictionary中为设计令牌添加多单位(px/rem)输出

解决Amazon Style Dictionary混合尺寸单位的问题

问题根源

使用scss默认transformGroup时,内置的size/pxToRem转换会把所有尺寸数值(哪怕你写了px单位)都强制转成rem,所以你的14px会被改成14rem。要实现部分用px、部分用rem,必须自定义转换逻辑来精准控制。

具体解决步骤

1. 修改config.json,替换默认转换

直接去掉transformGroup: "scss",手动指定transform列表,同时添加自定义的尺寸转换规则:

{
  "source": ["src/styledictionary/tokens/**/*.json"],
  "transforms": {
    "custom/size/unitControl": {
      "type": "value",
      "matcher": (token) => {
        // 只处理不带px单位的size类令牌
        return token.attributes.category === 'size' && typeof token.value === 'string' && !token.value.includes('px');
      },
      "transformer": (token) => `${token.value}rem`
    }
  },
  "platforms": {
    "scss": {
      "transforms": [
        "attribute/cti",
        "name/cti/kebab",
        "custom/size/unitControl", // 用自定义转换替代默认的size/pxToRem
        "color/hex",
        "time/seconds",
        "content/icon"
      ],
      "buildPath": "src/styles/tokens/",
      "files": [{
        "destination": "_variables.scss",
        "format": "scss/variables"
      }]
    }
  }
}

2. 令牌定义保持原样即可

你的原始令牌文件不需要修改,带px的会保留原单位,不带单位的会自动加上rem:

{
  "size": {
    "font": {
      "xss": { "value": "0.66" },
      "xs": { "value": "0.85" },
      "s": { "value": "1" },
      "m": { "value": "1.14" },
      "l": { "value": "1.43" },
      "xl": { "value": "1.71" },
      "xxl": { "value": "2.29" },
      "base": { "value": "14px"}
    }
  }
}

3. 生成结果验证

执行style dictionary build后,生成的SCSS变量会符合预期:

// Do not edit directly
// Generated on Wed, 03 Jan 2024 10:40:20 GMT

$size-font-xss: 0.66rem;
$size-font-xs: 0.85rem;
$size-font-s: 1rem;
$size-font-m: 1.14rem;
$size-font-l: 1.43rem;
$size-font-xl: 1.71rem;
$size-font-xxl: 2.29rem;
$size-font-base: 14px;

进阶优化(可选)

如果需要更精准的单位控制,可以给令牌添加attributes标记目标单位:

{
  "size": {
    "font": {
      "xss": { "value": "0.66", "attributes": {"targetUnit": "rem"} },
      "base": { "value": "14", "attributes": {"targetUnit": "px"} }
    }
  }
}

然后修改自定义转换的matcher和transformer:

"matcher": (token) => {
  return token.attributes.category === 'size' && token.attributes.targetUnit === 'rem';
},
"transformer": (token) => `${token.value}rem`

这样不带targetUnit或者标记为px的令牌,会直接输出数值+对应单位。

内容的提问来源于stack exchange,提问作者DFX Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:06:29