SASS 使用扩展和混合为相同的 class 生成两个单独的规则

SASS generates two separate rules for same class using extend and mixins

在此 SCSS 代码中,我使用 mixin btn-structure 并扩展 %red-color 以将所有声明置于一个 class 下,这与我的预期相反 SCSS 输出相同的两个单独规则class 如下输出所示:

%red-color{
  color: red }

@mixin btn-structure 
  ($text-case: null, $text-shadow: null, $decoration: none ){

display: inline-block;

  text: {
          decoration: $decoration;
            transform: $text-case;
            shadow: $text-shadow }

}

.link-btn{
  @include btn-structure($text-case: 'uppercase', $decoration: underline);
  @extend %red-color
}

输出

.link-btn {
  color: red;
}

.link-btn {
  display: inline-block;
  text-decoration: underline;
  text-transform: "uppercase";
}

我不希望 SASS 输出属于同一 class 的两个单独规则 如何让 SASS 输出属于一个 class 的一个规则].

这是 Sass @extend 的 use-case 的实际行为。

说明

为了清楚起见,请按以下方式更新您的代码

%red-color{
  color: red
}

@mixin btn-structure ($text-case: null, $text-shadow: null, $decoration: none ){
  display: inline-block;
  text: {
    decoration: $decoration;
    transform: $text-case;
    shadow: $text-shadow 
  }
}

.link-btn{
  @extend %red-color;
  @include btn-structure($text-case: 'uppercase', $decoration: underline);
}

.test-class{
  @extend %red-color;
  @include btn-structure($text-case: 'uppercase', $decoration: underline);
}

哪个会编译为,

.link-btn, .test-class {
  color: red;
}

.link-btn {
  display: inline-block;
  text-decoration: underline;
  text-transform: "uppercase";
}

.test-class {
  display: inline-block;
  text-decoration: underline;
  text-transform: "uppercase";
}

如您所见,@extend习惯于"share a set of CSS properties from one selector to another",可以组合在一起(.link-btn, .test-class)。然而,@include 用于在任何需要的地方插入样式,这不是 clubbed。

解决方案

根据您的要求,您可以求助于 @include 并声明一个 mixin @mixin red-color,如下所示,

%red-color{
  color: red
}

@mixin red-color{
  color: red
}

@mixin btn-structure ($text-case: null, $text-shadow: null, $decoration: none ){
  display: inline-block;
  text: {
    decoration: $decoration;
    transform: $text-case;
    shadow: $text-shadow 
  }
}

.link-btn{
  @include red-color;
  @include btn-structure($text-case: 'uppercase', $decoration: underline);
}

输出

而编译后的 css 将是,

.link-btn {
  color: red;
  display: inline-block;
  text-decoration: underline;
  text-transform: "uppercase";
}

希望这对您有所帮助。