【问题标题】:making node sass generate a class but also a mixin?让 node sass 生成一个类但也生成一个 mixin?
【发布时间】:2021-02-23 02:34:38
【问题描述】:

我对 sass 很陌生,我在想如果使用一些变量,我可以生成一些实用程序类和 mixin,我可以在 html 中使用,也可以在另一个 sass 文件中使用,而无需导入所有样式。

所以有两个问题:

  1. 我看到,如果我导入“_color.scss”,所有类都会自动添加到导入的文件中。有什么方法可以输出我想要的吗?我知道你可以通过一些节点扩展来做到这一点,但这不是我想要的,想要一些可以与 sass 扩展一起使用的东西。

  2. 这就是我想要实现的目标:

_colors 文件:

$primary: black;
$secondary: blue;

//generate the classes and the mixins with the name of the variables like:
.bg-primary {
  background-color: $primary;
}

@mixin bg-primary {
  background-color: $primary;
}

因此,我可以通过将类导入根目录来使用颜色,也可以只在组件中使用 mixin 而无需导入所有类。可能有更简单的方法可以做到这一点,因此欢迎任何替代方法。

更新:

这是实用程序 mixin:

@mixin u($prop, $value: null) {
  @if ($prop and $value) {
      #{$prop}: call($prop, $value);
  } @else {
    .u-#{$prop} {
      @each $item, $value in $color {
        &-#{$item} {
          #{$prop}: $value;
        };
      }
    }
  } 
}

这是更改的颜色文件:

    $color: (
  primary-main: rgb(25, 118, 210),
  secondary-main: rgb(220, 0, 78),
  error-main: rgb(244, 67, 54),
  warning-main: rgb(255, 152, 0),
  info-main: rgb(33, 150, 243),
  success-main: rgb(76, 175, 80),
  text-primary: rgba(0, 0, 0, 0.87),
  text-secondary: rgba(0, 0, 0, 0.54),
  text-disabled: rgba(0, 0, 0, 0.38),
);

@function color($value:null) {
  @if($value) {
    @if map-has-key($color, $value) {
      @return map-get($map: $color, $key: $value);
    }
  }
    @return $color
};

现在的问题是,对于我想要的每个属性,我都需要创建一个具有相同名称的函数。有什么办法可以使这部分动态化?所以我不需要为字体、bg 等创建函数...

【问题讨论】:

    标签: css sass


    【解决方案1】:

    知道了,

    所以我将所有标记聚合在一张地图中。

    然后我可以这样做:

    @mixin u($prop, $value: null) {
      @if ($prop and $value) {
          #{$prop}: get-tokens($tokens, $prop, $value);
      } @else {
        .u-#{$prop} {
          @each $item, $value in map-get($tokens, $prop) {
            &-#{$item} {
              #{$prop}: $value;
            };
          }
        }
      } 
    }
    

    代币:

    $tokens:(
      border-color: $color,
      color: $color,
      background-color: $color,
      font-size: $font-size,
      font-weight: $font-weight,
      font-family: $font-family,
    );
    
    @function get-tokens ($map, $keys...) {
      @if type-of($map) != 'map' {
        @error 'The argument $map: `#{$map}` is of incorrect type: `#{type-of($map)}`. Type of `Map` is required!';
      }
    
      @each $key in $keys {
        $map: map-get($map, $key);
      }
    
      @return $map;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2014-01-02
      • 2022-11-11
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多