如何校验媒体查询 (prefers-color-scheme) 与类名切换并存时的冲突?

解读

国内中大型前端团队普遍采用“系统主题 + 手动主题”双轨制:

  1. 媒体查询 @media (prefers-color-scheme: dark) 负责跟随系统;
  2. 业务侧通过 <html class="theme-dark"> 让用户手动覆盖。

两条通路同时存在时,极易出现“同一颜色令牌被重复定义、优先级颠倒、选择器权重爆炸”三类冲突。面试时,面试官想确认候选人能否:

  • 用 Stylelint 把“潜在冲突”转成“可静态分析的代码坏味道”;
  • 不依赖运行时,就能在 CI 阶段把问题卡死;
  • 给出的方案能直接落地到现有 Webpack / Vite 流水线,而非纸上谈兵。

知识点

  1. Stylelint 插件体系:自定义规则可访问 PostCSS AST,也能拿到 root.walkAtRules('media') 与 root.walkRules 的完整节点。
  2. 冲突模型:
    • 重复声明:同一 CSS 变量或属性在媒体查询与类选择器里被重新定义;
    • 权重倒挂:媒体查询选择器权重低于类选择器,导致用户切回系统主题时样式不生效;
    • 作用域污染:媒体查询内改的是 :root,类切换却改局部作用域,变量继承链断裂。
  3. 国内常用方案:
    • 命名约定:BEM 风格 theme-dark、CSS Modules dark_xxx、CSS-in-JS dark:xxx;
    • 变量系统:CSS 变量 --color-primary 统一收口;
    • 构建策略:PostCSS 插件 postcss-theme-colors 做编译期分流,Stylelint 做校验兜底。
  4. Stylelint 自定义规则开发:
    • 用 stylelint.utils.report 上报错误;
    • 用 stylelint.utils.validateOptions 做参数校验;
    • 用 context.fix 提供自动修复,把冲突代码注释掉或提升到统一作用域。

答案

落地步骤拆成“三步走”,每一步都给出可复制的代码片段,方便面试时手撕。

第一步:建立“冲突字典”
在 stylelint.config.js 里声明哪些变量/属性不允许在双轨里同时出现:

const conflictMap = {
  '--color-bg': true,
  '--color-text': true,
  'background-color': ['.theme-dark', '.theme-light']
};

第二步:写一条自定义规则 plugin/no-theme-conflict

const stylelint = require('stylelint');
const { pluginNamespace } = stylelint.utils;

const ruleName = 'plugin/no-theme-conflict';
const messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: (prop) => `属性 ${prop} 在媒体查询与类切换里同时定义,存在冲突`
});

module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOption = {}, context) {
  return (root, result) => {
    const validOptions = stylelint.utils.validateOptions(result, ruleName, {
      actual: primaryOption,
      possible: [true]
    });
    if (!validOptions) return;

    const mediaProps = {};   // 按属性名记录媒体查询节点
    const classProps  = {};  // 按属性名记录类切换节点

    root.walkAtRules('media', atRule => {
      if (atRule.params.includes('prefers-color-scheme')) {
        atRule.walkDecls(decl => {
          if (conflictMap[decl.prop]) {
            mediaProps[decl.prop] = decl;
          }
        });
      }
    });

    root.walkRules(rule => {
      if (rule.selector.includes('.theme-dark') || rule.selector.includes('.theme-light')) {
        rule.walkDecls(decl => {
          if (conflictMap[decl.prop]) {
            classProps[decl.prop] = decl;
          }
        });
      }
    });

    Object.keys(mediaProps).forEach(prop => {
      if (classProps[prop]) {
        stylelint.utils.report({
          message: messages.rejected(prop),
          node: classProps[prop],
          result,
          ruleName
        });
        if (context.fix) {
          // 自动修复策略:把类切换里的声明注释掉,强制走媒体查询
          classProps[prop].value = `/* disabled by stylelint */ ${classProps[prop].value}`;
        }
      }
    });
  };
});

第三步:接入流水线

// stylelint.config.js
module.exports = {
  plugins: ['./lib/stylelint-no-theme-conflict'],
  rules: {
    'plugin/no-theme-conflict': [true, { severity: 'error' }]
  }
};

在 package.json 里加脚本:

"scripts": {
  "lint:css": "stylelint 'src/**/*.{css,scss}' --max-warnings 0",
  "lint:css:fix": "stylelint 'src/**/*.{css,scss}' --fix"
}

GitHub Actions 卡点:

- name: Lint CSS
  run: npm run lint:css

至此,任何“媒体查询 + 类名”重复定义都会在 PR 阶段被拦下,并支持一键自动修复。

拓展思考

  1. 权重策略再细化:
    如果团队允许“类切换 > 媒体查询”,可把修复逻辑反转——注释媒体查询而非类切换,并在规则配置里加 strategy: 'class-first' 参数,让规则可配。
  2. 颜色令牌溯源:
    结合 Figma Tokens 生成的 theme.json,在 Stylelint 插件里做“来源校验”,防止设计师删了令牌而开发还在用,实现设计-代码一致性闭环。
  3. 灰度发布场景:
    国内常按“地域 + 版本”灰度主题,PostCSS 可在编译期打出两份 CSS,Stylelint 插件可扩展为“多主题并发校验”,确保 dark、blue、golden 三套主题不会交叉污染。
  4. 低代码平台:
    在阿里、腾讯低代码搭建场景,样式是可视化拖拽生成的,AST 里缺少源码位置。此时可把 Stylelint 插件包装成云函数,实时返回冲突行列号,供搭建器在前端画布上标红提示,实现“零源码”也能静态分析。