带有默认值的Sass配置图

问题描述 投票:0回答:3

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

$text-color: #000 !default;

为了测试覆盖,我创建了一个新项目,首先在其中声明变量的覆盖,然后导入“基本”sass 文件。

$text-color: #0074b;    
@import "base-file";

但我也想使用地图进行配置,但随后我无法使覆盖正常工作。我应该如何使用可以覆盖的配置映射?

$colors: (text-color: #000, icon-color: #ccc );

在 #000 之后添加 !default 会出现编译错误:

expected ")", was "!default,")
在 ) 之后添加 !default 不会产生错误,但变量也不会被覆盖。

对我做错了什么有什么想法吗?

sass compass-sass
3个回答
10
投票

我认为标准 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,
));

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
);

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


0
投票

在地图中使用默认值是不正确的。

无法将默认设置为某个键值,而是设置为整个地图。这就是为什么它对你不起作用。

$colors: (
text-color: #000, 
background-color: #ccc) !default;

enter image description here

如您在第一张图片中所见,采用默认值。 在第二张图片中,当您找不到另一张图片时,请使用默认地图

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.