具有默认值的Sass配置映射

P3a*_*uts 2 sass compass-sass

我正在使用SASS创建css,并希望其他开发人员可以通过更改sass变量来创建自定义css.当我在我的基本文件中使用这样的单个变量时,这很好用:

$text-color: #000 !default;
Run Code Online (Sandbox Code Playgroud)

为了测试覆盖,我创建了一个新项目,首先声明变量的覆盖,然后导入"base"sass文件.

$text-color: #0074b;    
@import "base-file";
Run Code Online (Sandbox Code Playgroud)

但我也想使用地图进行配置,但是我没有让覆盖工作.我应该如何使用可以覆盖的配置图?

$colors: (text-color: #000, icon-color: #ccc );
Run Code Online (Sandbox Code Playgroud)

在#000之后添加!default会给我一个编译错误:expected ")", was "!default,") 添加!default之后没有给出错误但是变量也没有被覆盖.

关于我做错了什么的任何想法?

kit*_*lku 9

Bootstrap 解决了这个问题:

$grays: () !default;
// stylelint-disable-next-line scss/dollar-variable-default
$grays: map-merge(
  (
    "100": $gray-100,
    "200": $gray-200,
    "300": $gray-300,
    "400": $gray-400,
    "500": $gray-500,
    "600": $gray-600,
    "700": $gray-700,
    "800": $gray-800,
    "900": $gray-900
  ),
  $grays
);
Run Code Online (Sandbox Code Playgroud)

https://github.com/twbs/bootstrap/blob/v4.1.3/scss/_variables.scss#L23


Dan*_*non 8

我不认为您想要的功能存在于标准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';
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

$map: defaultTo($map, (
    key1 : value1,
    key2 : value2
));
Run Code Online (Sandbox Code Playgroud)

然后,如果你有一个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));
}
Run Code Online (Sandbox Code Playgroud)

输出的CSS:

.element { background: white; color: blue; }
Run Code Online (Sandbox Code Playgroud)

所以你会根据你在问题中所说的那样使用它:

$colors: defaultTo($colors, (
    text-color: #000,
    icon-color: #ccc,
));
Run Code Online (Sandbox Code Playgroud)