2021-08-24 22:15:44
要在 Stylelint 中阻止 top、bottom、left 和 right 属性自动转换为 inset,需禁用 declaration-block-no-redundant-longhand-properties 规则。以下是具体配置方法及原理说明:
核心解决方案在 Stylelint 配置文件(如 .stylelintrc.json 或 stylelint.config.js)中,将 declaration-block-no-redundant-longhand-properties 规则设为 null:
{ "rules": { "declaration-block-no-redundant-longhand-properties": null }}或通过命令行参数覆盖(如使用 --config 时):
stylelint "/*.css" --config '{"rules":{"declaration-block-no-redundant-longhand-properties":null}}'规则作用原理默认行为:Stylelint 的 declaration-block-no-redundant-longhand-properties 规则默认启用(值为 true),它会检测 CSS 中是否存在可简写的长属性(如 top/bottom/left/right),并建议替换为 inset 简写属性。例如:
/* 触发警告的代码 */.element { top: 0; bottom: 0; left: 0; right: 0;}会被建议改为:
.element { inset: 0;}禁用后的效果:将规则设为 null 后,Stylelint 会停止检查长属性与简写属性的冗余关系,允许同时保留 top/bottom/left/right 和 inset。例如以下代码将不再触发警告:
.element { top: 10px; left: 20px; inset: 0; /* 允许与长属性共存 */}需要精确控制定位:当同时使用 inset 和长属性实现不同方向的覆盖(如动态修改 top 但保留 inset 的其他值)时,禁用规则可避免意外覆盖。
兼容旧代码或框架:某些遗留系统或 UI 框架可能依赖长属性实现特定逻辑,禁用规则可确保代码兼容性。
团队规范要求:若团队约定优先使用长属性(如提高可读性),需通过此配置覆盖默认规则。
规则优先级:若配置中同时存在 declaration-block-no-redundant-longhand-properties 的 true/false 值和 null,null 会优先生效,完全禁用规则。
与其他规则的交互:此配置仅影响长属性与简写属性的冗余检查,不会影响其他规则(如 property-no-unknown)。若需同时禁用其他相关规则,需单独配置。
版本兼容性:
Stylelint v14+ 完全支持此配置。
旧版本(如 v13)可能需通过 "declaration-block-no-redundant-longhand-properties": [false] 实现类似效果。
若需更精细的控制(如仅允许特定长属性与 inset 共存),可结合 stylelint-declaration-block-no-ignored-properties 插件自定义规则,但需额外安装依赖:
npm install stylelint-declaration-block-no-ignored-properties --save-dev配置示例:
{ "plugins": ["stylelint-declaration-block-no-ignored-properties"], "rules": { "plugin/declaration-block-no-ignored-properties": [true, { "ignoreProperties": ["top", "bottom"] // 仅允许 top/bottom 与 inset 共存 }] }}通过上述配置,可彻底解决 Stylelint 自动合并定位属性为 inset 的问题,同时保持代码的灵活性和可维护性。