重新安装依赖后,sass报警告Sass‘s behavior for declarations that appear after nested rules will be changing
目录
[TOC]
今天拉取代码,重新执行pnpm i安装依赖后。发现终端出来了一堆sass的警告,
Deprecation Warning: Sass’s behavior for declarations that appear
after nested rules will be changing to match the behavior specified by
CSS in an upcoming version. To keep the existing behavior, move the
declaration above the nested rule. To opt into the new behavior, wrap
the declaration in& {}.More info: sass-lang.com/d/mixed-dec…
┌──> node_modules\element-plus\theme-chalk\src\mixins_button.scss
159│ padding: padding-horizontal; │
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ declaration ╵
┌──> node_modules\element-plus\theme-chalk\src\button.scss 71 │ ┌ &
- & { 72 │ │ margin-left: 12px; 73 │ │ } │ └─── nested rule
原因
根据给的错误信息,在sass官网可以看到说明。sass新版本有破坏性变更。
Sass: Breaking Change: Mixed Declarations
简单来说就是,sass为了迎合css的行为,对原来的嵌套规则了做了限定。但是很多组件库都是旧的写法。包括我们项目常用的elemnet-plus。可以在错误信息看到,很多指向的都是element的组件样式。
相关issues讨论 github.com/element-plu…
解决方法
这个警告信息是关于Sass编译器的一个即将改变的行为。Sass是一种流行的CSS预处理器,它允许你使用变量、嵌套规则等特性来编写更简洁、更易于维护的CSS代码。
警告内容解释
- Deprecation Warning : 表示这是一个废弃警告,意味着在未来的版本中,某些行为将会改变。
- Sass's behavior for declarations that appear after nested rules : 这指的是在嵌套规则之后出现的声明。
- will be changing to match the behavior specified by CSS : 表示Sass将改变其行为,以匹配CSS规范中的行为。
- To keep the existing behavior : 如果你希望保持当前的行为,需要将声明移动到嵌套规则之前。
- To opt into the new behavior : 如果你希望采用新的行为,可以将声明用
& {}包裹起来。
方案一
知道原因后,我认为这样的变更覆盖面太广,很多组件库不可能第一时间做出更新,况且还有自己写的代码还有不再维护的组件库。所以要想解决这个问题,最好的办法就是降低sass的版本。
版本是在1.77.7开始的。 所以可以固定sass的版本在1.77.6之前。
方案二
移动声明 :将声明移动到嵌套规则之前。例如:
.parent {
.child {
// 嵌套规则
}
// 移动声明到嵌套规则之前
color: red;
}
使用 & {} 包裹 :如果你想采用新的行为,可以将声明用 & {} 包裹起来。例如:
.parent {
& {
color: red;
}
.child {
// 嵌套规则
}
}
示例
假设你有以下Sass代码:
.parent {
.child {
display: block;
}
color: red;
}
为了避免警告,你可以这样修改:
.parent {
& {
color: red;
}
.child {
display: block;
}
}
这样, color: red; 将被正确地应用到 .parent 选择器上,而不是仅仅应用到 .child 选择器上。
注意
- 这种改变可能会影响你的CSS输出,因此在更新Sass版本之前,最好检查一下你的代码,确保没有意外的行为改变。
- 如果你使用的是Sass的编译工具或构建系统,确保它们也支持这些新的行为。