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

如何用Stylelint创建自定义SCSS规则:将媒体查询移至类外部

创建自定义SCSS Lint规则:强制媒体查询位于类选择器外部

要实现这条规则,你需要基于SCSS Lint的扩展机制编写自定义Ruby规则,步骤如下:

1. 编写自定义规则代码

创建一个Ruby文件(比如no-nested-media-inside-classes.rb),实现规则逻辑:

class ScssLint::Linter::NoNestedMediaQueriesInsideClasses < ScssLint::Linter
  include ScssLint::LinterRegistry

  def visit_media_query(node)
    # 向上遍历父节点链,检查媒体查询是否嵌套在类选择器内部
    parent_node = node.parent
    while parent_node
      # 判断父节点是否是类选择器的规则块
      if parent_node.is_a?(Sass::Tree::RuleNode) && 
         parent_node.selectors.any? { |sel| sel.include?('.') }
        add_lint(node, '媒体查询不能嵌套在类选择器内部,请将其移至类选择器外部')
        break
      end
      parent_node = parent_node.parent
    end
  end
end

代码说明

  • 继承SCSS Lint的基础Linter类并加入注册器,确保工具能识别这条自定义规则
  • visit_media_query方法会遍历SCSS抽象语法树中的所有媒体查询节点
  • 通过向上遍历父节点,判断当前媒体查询是否被包含在类选择器(以.开头的选择器)的规则块内
  • 如果检测到违规,就抛出指定的错误提示

2. 配置SCSS Lint启用规则

在项目的.scss-lint.yml配置文件中,添加以下内容:

# 指定自定义规则所在的目录(如果规则文件不在默认路径下)
plugin_directories:
  - ./lib/scss_linters

linters:
  # 启用自定义规则
  NoNestedMediaQueriesInsideClasses:
    enabled: true

3. 验证规则效果

合规代码(无错误提示)

.class-name {
    background-color: green;
}

@media only screen and (max-width: 600px) {
  .class-name {
    background-color: lightblue;
  }
}

违规代码(触发错误提示)

.class-name {
    background-color: green;

    @media only screen and (max-width: 600px) {  
        background-color: lightblue;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:10:38