如何检测 pages/_app 中意外引入全局 CSS?
解读
在 Next.js 项目里,只有 pages/_app(或 app/layout)被官方允许“顶层导入”全局样式文件。一旦业务同学在其他页面、组件甚至 utils 里写了一句 import '../styles/globals.css',打包后会把整块样式直接塞进 <head>,造成样式污染、优先级混乱、HMR 变慢,且很难被 Code Review 肉眼发现。
面试官问“如何用 Stylelint 检测”,本质考察两件事:
- 是否知道 Stylelint 只能“看见”当前文件内容,无法直接感知“谁在哪个入口引入了我”;
- 能否把“业务规则”抽象成“静态可识别的代码特征”,并用 Stylelint 插件机制落地。
国内大厂通常把这条规则写进 MR 门禁,一旦触发直接阻断流水线,因此答案必须可自动化、可修复、可插拔。
知识点
- Stylelint 插件体系:自定义规则通过
stylelint.createPlugin注册,返回{ ruleName, rule }。 - PostCSS AST:Stylelint 内置
postcss.parse,每个@import或import语句会被解析成AtRule节点,文件名挂在AtRule.params上。 - 文件路径上下文:
root.source.input.file给出当前被扫描文件的绝对路径;借助 Node 的path.relative可判断其是否位于pages/_app或app/layout。 - 国内目录习惯:很多团队把
_app放在src/pages/下,也有直接放pages/;规则需要支持可配置allowedEntryGlobs。 - 自动修复思路:把非法的
@import 'xxx/globals.css'改成import styles from 'xxx/globals.css?module'或直接删除节点,并给出提示。 - 与 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。
拓展思考
- 微前端场景:主应用与多个子应用共仓库,需要把
allowedEntryGlobs扩展成数组,支持apps/*/pages/_app。 - Monorepo + pnpm:全局样式可能放在
packages/ui/index.css,规则需把import '@org/ui/index.css'也识别为“全局 CSS”。 - 与 eslint-plugin-import 联动:Stylelint 只处理样式文件,若团队在
.js里写import 'antd/dist/antd.css',可再写一条 ESLint 规则no-restricted-imports做二次校验,形成双保险。 - 性能优化:在 CI 阶段先用
git diff --name-only拿到变更列表,再stylelint --cache --cache-strategy content只扫描增量文件,把检测耗时从 30s 降到 3s。 - 提示友好:在 VS Code 的 Stylelint 扩展里配置
stylelint.validate: ['css', 'scss', 'javascript', 'typescript'],保存时即时标红,并给出“快速修复:移至 _app”的 CodeAction,彻底杜绝“意外引入”。