sass的模块化与覆盖可配置样式

376 阅读1分钟

架构模块: basis.scss
产品模块: product.scss
实施模块: pi.scss

需求背景:
basis.scss是根据UI写出的所有组件的基础样式。
product.scss是产品开发时引用basis.scss,但有些时候需要特殊修改,所以需要能覆盖basis.scss的某些样式。
pi.scss是实施时面向客户定制修改的样式,优先级最高,既可以覆盖product的样式,也可以覆盖basis的样式。

这里就涉及到sass的模块化的知识点,官网有相关介绍

@use
@forward

demo:

// basis.scss
@use 'sass:math';

$dangercolor: red !default;
$font-size: 14px !default;
$ms-ratio: 2.0 !default;

$font-size-px-lv1: $font-size * math.pow($ms-ratio, 1) !default;
$font-size-px-lv4: $font-size * math.pow($ms-ratio, 1) * 0.2 !default;

@mixin colorTest {
    height: $font-size;
    color: red;
}

.height-100 {
    height: $font-size-px-lv1;
    font-size: $font-size;
}

.height {
    @extend .height-100;
}
// product.scss
@forward 'basis.scss' with (
    $font-size: 30px !default,
    $dangercolor: green !default,
);
@use 'basis.scss';


.width-100 {
    width: basis.$font-size;
    @include basis.colorTest;
}
// pi.scss
@use 'product.scss' with (
    $font-size: 50px,
    $dangercolor: rgb(95, 61, 61),
);

使用:

// demo.component.scss
@use '../scss/pi.scss' as pi;
@use '../scss/basis.scss' as basis;

.red-box {
    font-size: basis.$font-size-px-lv4;
}

.danger-box {
    height: 100px;
    width: 100px;
    background-color: basis.$dangercolor;
}
// demo.component.html
<div>
  <div class="red-box width-100">
    <span>Test Box</span>
  </div>
  <div class="height-100">
    <span>lv1 Box</span>
  </div>
  <div class="height">
    <span>lv4 Box</span>
  </div>
  <div class="danger-box"></div>
</div>

其中有个比较关键的知识点是,product既需要引入basis的基础样式,又需要把basis的样式转发给pi,同时pi也要能够修改。
product.scss 文件里需要 @forward basis.scss, 同时必须加上!default, 这样pi.scss在@use product.scss的时候才可以with修改。
因为同时运用到了@forward@use 所以@forward 必须在前面

sass模块化相关介绍