如何检测 pages/_app 中意外引入全局 CSS?

解读

在 Next.js 项目里,只有 pages/_app(或 app/layout)被官方允许“顶层导入”全局样式文件。一旦业务同学在其他页面、组件甚至 utils 里写了一句 import '../styles/globals.css',打包后会把整块样式直接塞进 <head>,造成样式污染、优先级混乱、HMR 变慢,且很难被 Code Review 肉眼发现。
面试官问“如何用 Stylelint 检测”,本质考察两件事:

  1. 是否知道 Stylelint 只能“看见”当前文件内容,无法直接感知“谁在哪个入口引入了我”;
  2. 能否把“业务规则”抽象成“静态可识别的代码特征”,并用 Stylelint 插件机制落地。
    国内大厂通常把这条规则写进 MR 门禁,一旦触发直接阻断流水线,因此答案必须可自动化、可修复、可插拔。

知识点

  1. Stylelint 插件体系:自定义规则通过 stylelint.createPlugin 注册,返回 { ruleName, rule }。
  2. PostCSS AST:Stylelint 内置 postcss.parse,每个 @import 或 import 语句会被解析成 AtRule 节点,文件名挂在 AtRule.params 上。
  3. 文件路径上下文:root.source.input.file 给出当前被扫描文件的绝对路径;借助 Node 的 path.relative 可判断其是否位于 pages/_app 或 app/layout。
  4. 国内目录习惯:很多团队把 _app 放在 src/pages/ 下,也有直接放 pages/;规则需要支持可配置 allowedEntryGlobs。
  5. 自动修复思路:把非法的 @import 'xxx/globals.css' 改成 import styles from 'xxx/globals.css?module' 或直接删除节点,并给出提示。
  6. 与 GitLab CI / GitHub Actions 集成:在 stylelint --fix 后加 --custom-formatter 输出 CodeClimate JSON,平台可直接展示违规行。

答案

实现一条自定义规则 plugin/no-global-css-in-non-app,核心逻辑如下:

// stylelint-plugin-no-global-css-in-non-app.js
const stylelint = require('stylelint');
const path = require('path');
const micromatch = require('micromatch');

const ruleName = 'plugin/no-global-css-in-non-app';
const messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: (file) => `全局样式文件 '${file}' 只能在 pages/_app 或 app/layout 中引入`
});

const meta = {
  fixable: true
};

function rule(primaryOption, secondaryOption = {}) {
  return (root, result) => {
    const validOptions = stylelint.utils.validateOptions(
      result,
      ruleName,
      { actual: primaryOption, possible: [true] },
      {
        actual: secondaryOption,
        possible: {
          allowedEntryGlobs: [Array]
        },
        optional: true
      }
    );
    if (!validOptions) return;

    const allowedEntryGlobs = secondaryOption.allowedEntryGlobs || [
      '**/pages/_app.{js,jsx,ts,tsx}',
      '**/app/layout.{js,jsx,ts,tsx}'
    ];

    const currentFile = root.source.input.file;
    const isEntry = allowedEntryGlobs.some(g => micromatch.isMatch(currentFile, g));
    if (isEntry) return;

    root.walkAtRules('import', atRule => {
      const importPath = atRule.params.replace(/["']/g, '');
      if (importPath.endsWith('.css') || importPath.includes('.css?')) {
        stylelint.utils.report({
          message: messages.rejected(importPath),
          node: atRule,
          result,
          ruleName,
          fix() {
            atRule.remove(); // 保守修复:直接移除非法引入
          }
        });
      }
    });
  };
}

module.exports = stylelint.createPlugin(ruleName, rule);

在 .stylelintrc.js 中启用:

module.exports = {
  plugins: ['./stylelint-plugin-no-global-css-in-non-app'],
  rules: {
    'plugin/no-global-css-in-non-app': [true, {
      allowedEntryGlobs: [
        '**/src/pages/_app.{js,jsx,ts,tsx}',
        '**/src/app/layout.{js,jsx,ts,tsx}'
      ]
    }]
  }
};

运行 npx stylelint "**/*.{css,scss,less,js,jsx,ts,tsx}" --fix,即可在控制台与 CI 报告中精准定位“非入口文件引入全局 CSS”的违规行,并自动删除对应 @import。

拓展思考

  1. 微前端场景:主应用与多个子应用共仓库,需要把 allowedEntryGlobs 扩展成数组,支持 apps/*/pages/_app。
  2. Monorepo + pnpm:全局样式可能放在 packages/ui/index.css,规则需把 import '@org/ui/index.css' 也识别为“全局 CSS”。
  3. 与 eslint-plugin-import 联动:Stylelint 只处理样式文件,若团队在 .js 里写 import 'antd/dist/antd.css',可再写一条 ESLint 规则 no-restricted-imports 做二次校验,形成双保险。
  4. 性能优化:在 CI 阶段先用 git diff --name-only 拿到变更列表,再 stylelint --cache --cache-strategy content 只扫描增量文件,把检测耗时从 30s 降到 3s。
  5. 提示友好:在 VS Code 的 Stylelint 扩展里配置 stylelint.validate: ['css', 'scss', 'javascript', 'typescript'],保存时即时标红,并给出“快速修复:移至 _app”的 CodeAction,彻底杜绝“意外引入”。