我正在使用 SASS 创建 css,并希望其他开发人员可以通过更改 sass 变量来创建自定义 css。当我在我的基本文件中使用这样的单个变量时,这很好用:
$text-color: #000 !default;
为了测试覆盖,我创建了一个新项目,我首先在其中声明变量的覆盖,然后导入“基本”sass 文件。
$text-color: #0074b;
@import "base-file";
但我也想使用 map 进行配置,但是我没有让覆盖工作。我应该如何使用可以覆盖的配置映射?
$colors: (text-color: #000, icon-color: #ccc );
在#000 之后添加 !default 给我一个编译错误:
expected ")", was "!default,")
在 ) 之后添加 !default 不会出错,但变量也不会被覆盖。关于我做错了什么的任何想法?
最佳答案
我认为标准 Sass 中不存在您想要的功能。我构建了这个函数,尽管它可以满足您的要求:
//A function for filling in a map variable with default values
@function defaultTo($mapVariable: (), $defaultMap){
//if it's a map, treat each setting in the map seperately
@if (type-of($defaultMap) == 'map' ){
$finalParams: $mapVariable;
// We iterate over each property of the defaultMap
@each $key, $value in $defaultMap {
// If the variable map does not have the associative key
@if (not map-has-key($mapVariable, $key)) {
// add it to finalParams
$finalParams: map-merge($finalParams, ($key : $value));
}
}
@return $finalParams;
//Throw an error message if not a map
} @else {
@error 'The defaultTo function only works for Sass maps';
}
}
用法:
$map: defaultTo($map, (
key1 : value1,
key2 : value2
));
然后,如果你有一些东西的 mixin,你可以做这样的事情:
@mixin someMixin($settings: ()){
$settings: defaultTo($settings, (
background: white,
text: black
);
background: map-get($settings, background);
color: map-get($settings, text);
}
.element {
@include someMixin((text: blue));
}
输出的 CSS:
.element { background: white; color: blue; }
所以你会根据你在问题中所说的那样使用它:
$colors: defaultTo($colors, (
text-color: #000,
icon-color: #ccc,
));
关于具有默认值的 Sass 配置映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26957753/