You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Sass编译器,使编译后的CSS规则间保留空行?

如何让Sass编译后的CSS在规则间保留空行以符合Stylelint校验

我有一个简单的SCSS文件:

.slogan {
  text-align: center;
  line-height: 36px;
  letter-spacing: 0;

  &-title {
    font-size: 30px;
    font-weight: 700;
  }

  &-detail {
    font-size: 22px;
    font-weight: 400;
  }
}

编译为CSS后输出如下:

.slogan {
  text-align: center;
  line-height: 36px;
  letter-spacing: 0;
} 
.slogan-title {  /* Expected empty line before rule */
  font-size: 30px;
  font-weight: 700;
}
.slogan-detail {  /* Expected empty line before rule */
  font-size: 22px;
  font-weight: 400;
}

Stylelint报出Expected empty line before rule(你描述里的at-rule应为笔误,实际是普通规则的校验)错误,需要让输出符合校验规则。我当前用npx sass scss:css --watch --no-source-map命令编译,请问能不能配置Sass编译器直接输出带规则间空行的CSS?


原生Sass无法直接配置规则间空行

你使用的npx sass属于Dart Sass,它的格式化选项仅包含--style(expanded/compressed等模式),即便用expanded模式,也不会自动在CSS规则之间添加空行,没有内置配置项支持这个需求。可以通过以下两种方式解决:

方案1:用PostCSS后处理编译后的CSS

通过PostCSS搭配格式化插件,给编译后的CSS自动添加规则间的空行:

  1. 安装依赖:
npm install postcss postcss-cli prettier --save-dev
  1. 在项目根目录创建postcss.config.js:
module.exports = {
  plugins: [
    require('prettier')
  ]
}
  1. 修改编译命令,并行监听Sass编译和PostCSS格式化:
    先安装concurrently来同时执行两个监听任务:
    npm install concurrently --save-dev
    
    然后在package.json的scripts中添加:
    "scripts": {
      "dev": "concurrently \"sass scss:css --watch --no-source-map\" \"postcss css/*.css --dir css --watch\""
    }
    
    之后运行npm run dev即可,Sass编译后的CSS会被PostCSS自动格式化,规则间会生成空行。

方案2:调整Stylelint规则适配编译结果

如果不想额外增加工具链,可以修改Stylelint规则,允许特定场景下规则前不需要空行:
在你的.stylelintrc.json(或其他Stylelint配置文件)中调整rule-empty-line-before规则:

{
  "rules": {
    "rule-empty-line-before": ["always", {
      "except": ["first-nested"],
      "ignore": ["after-comment"]
    }]
  }
}

这个配置会允许嵌套编译后的规则(比如.slogan-title紧跟.slogan)前不需要空行,同时保持其他场景的空行要求。


内容的提问来源于stack exchange,提问作者A1exandr Belan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:25:20