SCSS @mixin生成CSS颜色变量报错,求排查修正方法
问题分析与解决
问题描述
定义了如下SCSS主题颜色map:
$theme-colours: ( dark: ( primary: ( light: #32303b, base: #32303b, dark: #32303b, ), secondary: ( light: #201f26, base: #201f26, dark: #201f26, ), ), light: ( primary: ( light: #32303b, base: #32303b, dark: #32303b, ), secondary: ( light: #201f26, base: #201f26, dark: #201f26, ), ), );
编写的生成CSS主题变量的@mixin如下:
@mixin generateCssThemeVariables($themeName) { @each $theme, $colourType in $theme-colours { @if $theme == $themeName { @each $variation, $value in $colourType { --#{$colourType}-colour-#{$variation}: #{$value}; } } } }
调用@include generateCssThemeVariables("dark");时,期望输出:
--primary-colour-light: #32303b; --primary-colour-base: #32303b; --primary-colour-dark: #32303b; --secondary-colour-light: #201f26; --secondary-colour-base: #201f26; --secondary-colour-dark: #201f26;
但报错提示$colourType对应的map不是有效的CSS值。
错误原因
你的@mixin存在循环层级和变量命名的错误:
- 第一层
@each $theme, $colourType in $theme-colours中,$colourType实际是整个颜色分组的map(比如dark主题对应的(primary: (...), secondary: (...))) - 第二层
@each $variation, $value in $colourType里,$variation是primary/secondary这类键名,$value是它们对应的子map(比如(light: #32303b, ...)) - 错误地把
$colourType(一个map)直接插入到CSS变量名中,导致生成无效的变量名,触发报错。
修正后的@mixin
需要增加一层循环,遍历每个颜色类型下的具体色值项:
@mixin generateCssThemeVariables($themeName) { @each $theme, $colourGroups in $theme-colours { @if $theme == $themeName { // 遍历primary、secondary这类颜色分组 @each $colourType, $colourVariations in $colourGroups { // 遍历每个分组下的light/base/dark色值 @each $variation, $hexValue in $colourVariations { --#{$colourType}-colour-#{$variation}: #{$hexValue}; } } } } }
调用@include generateCssThemeVariables("dark");后,就能生成你期望的CSS变量。
内容的提问来源于stack exchange,提问作者CavemanDan
相关产品推荐
相关产品推荐

