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

SCSS循环动态拼接变量报错:未定义变量问题求助

Sass动态生成背景色样式报错的解决方案

问题场景

想通过循环$deeps数组,拼接已定义的$brand-primary-surface-*颜色变量,自动生成对应类名的背景色样式,但编译时触发了SassError: Undefined variable错误。

已定义的颜色变量

$brand-primary-surface-0: #fafafaff;
$brand-primary-surface-25: #f5f5f5ff;
$brand-primary-surface-50: #ebebebff;
$brand-primary-surface-75: #d8d8d8ff;
$brand-primary-surface-100: #c0c0c0ff;
$brand-primary-surface-200: #a1a1a1ff;
$brand-primary-surface-300: #767676ff;
$brand-primary-surface-400: #5c5c5cff;
$brand-primary-surface-600: #2e2e2eff;
$brand-primary-surface-700: #242424ff;
$brand-primary-surface-800: #1c1c1cff;
$brand-primary-surface-900: #151515ff;

循环数组与代码

$deeps: 0, 25, 50, 75, 100, 200, 300, 400, 500, 600, 700, 800, 900;

@each $deep in $deeps {
    .brand-primary-surface-#{$deep} {
        background-color: $brand-primary-surface-#{$deep};
    }
}

报错信息

ERROR in ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/components/Button/Button.scss undefined
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
   ╷
94 │ background-color: $brand-primary-surface-#{$deep};
   │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   ╵
  src\colors.scss 94:27 @import
  src\components\Button\Button.scss 1:9 root stylesheet

错误原因

  1. Sass预编译阶段不支持直接通过字符串拼接的方式引用变量($brand-primary-surface-#{$deep}这种写法无法被识别为已定义的变量);
  2. $deeps数组里包含500,但并没有定义对应的$brand-primary-surface-500变量,这也会触发未定义报错。

解决方法

方法一:用Sass映射(Map)重构变量(推荐)

把分散的颜色变量整合为一个Map,直接通过键值对获取颜色,彻底避免动态拼接变量名的问题:

// 把颜色变量重构为Map
$brand-primary-surfaces: (
    0: #fafafaff,
    25: #f5f5f5ff,
    50: #ebebebff,
    75: #d8d8d8ff,
    100: #c0c0c0ff,
    200: #a1a1a1ff,
    300: #767676ff,
    400: #5c5c5cff,
    600: #2e2e2eff,
    700: #242424ff,
    800: #1c1c1cff,
    900: #151515ff
);

// 循环Map生成样式
@each $deep, $color in $brand-primary-surfaces {
    .brand-primary-surface-#{$deep} {
        background-color: $color;
    }
}

方法二:使用变量获取函数(兼容旧项目)

如果没法重构现有变量,可以用Sass的variable-get()函数(注意新版Dart Sass已改用get-function()),同时要先移除数组中未定义的500:

// 移除数组中不存在对应变量的500
$deeps: 0, 25, 50, 75, 100, 200, 300, 400, 600, 700, 800, 900;

@each $deep in $deeps {
    $var-name: "brand-primary-surface-#{$deep}";
    .brand-primary-surface-#{$deep} {
        background-color: variable-get($var-name);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:02:54