如何提示将 style 提取到 <style jsx global>?
解读
面试官抛出这道题,并不是想听你背诵“把 CSS 粘过去就行”,而是在考察三件事:
- 你是否理解 Next.js / React 生态里“CSS-in-JS 全局污染”这一真实痛点;
- 你是否能把 Stylelint 的“规则设计”与“工程化落地”串起来,让机器替人做提醒;
- 你是否具备“自定义规则 + 自动修复”的闭环能力,而不是只停留在配置层面。
国内一线团队(阿里、字节、美团)在落地微前端、SSR、低代码平台时,都会把“全局样式逃逸”当成红线。Stylelint 作为 CI 门禁,必须能在提交前就给出精准提示,并一键修复,否则 review 成本极高。因此,这道题本质是“如何写一条自定义 Stylelint 规则,检测到裸全局选择器就报 ‘请提取到 <style jsx global>’,并且能自动帮开发者搬代码”。
知识点
-
Stylelint 规则三要素:
- meta(url、fixable、severity)
- createRule 回调,返回 { ruleName, rule }
- PostCSS AST 遍历钩子(Root→Rule→Selector)
-
裸全局选择器识别:
- 选择器不以父级作用域前缀(如 .page__、.component__)开头
- 命中 html、body、:root、*、#[id]、.[class] 等“明显是全局”的节点
- 过滤掉已在 /* style-jsx-global */ 注释标记内的代码,避免二次提示
-
自动修复(fix)实现:
- 通过 context.fix 判断是否可以修复
- 用 Root#append 把整段 Rule 节点移动到新建的全局作用域,并包裹成 <style jsx global> 模板字符串
- 返回 PostCSS LazyResult,让 Stylelint 在 --fix 阶段直接重写文件
-
国内工程链对接:
- 规则包发布到私有 npm(verdaccio/cnpm)
- 在 @company/stylelint-config-next 里默认开启该规则,severity 设为 error
- 与 husky + lint-staged 结合,禁止 push 未修复的分支
- 提供 VS Code 插件 snippet,一键生成 <style jsx global> 模板,降低心智负担
答案
-
创建自定义规则包 stylelint-plugin-next-global-style
目录结构:
src/rules/global-style-extract.js
src/index.js -
实现规则核心代码(节选)
// global-style-extract.js
const stylelint = require('stylelint');
const { utils } = stylelint;
const ruleName = 'plugin/global-style-extract';
const messages = utils.ruleMessages(ruleName, {
expected: (selector) => `全局选择器 "${selector}" 请提取到 <style jsx global>`
});
module.exports = stylelint.createPlugin(ruleName, function(primary, secondary, context) {
return (root, result) => {
root.walkRules(rule => {
// 简易全局判定
const isGlobal = /^(html|body|:root|\*|\[id=|\[class=)/.test(rule.selector);
if (!isGlobal) return;
// 已标记全局注释的跳过
if (rule.prev() && rule.prev().type === 'comment' && rule.prev().text.includes('style-jsx-global')) return;
const complaint = utils.report({
message: messages.expected(rule.selector),
node: rule,
result,
ruleName,
line: rule.source.start.line,
column: rule.source.start.column
});
// 自动修复
if (context.fix) {
// 生成新节点
const globalComment = root.constructor.comment({ text: 'style-jsx-global' });
const globalRule = rule.clone();
rule.remove(); // 删除原节点
root.append(globalComment, globalRule);
}
});
};
});
- 在 stylelint.config.js 中启用
module.exports = {
plugins: ['./node_modules/@company/stylelint-plugin-next-global-style'],
rules: {
'plugin/global-style-extract': [true, { severity: 'error' }]
}
};
- 运行
npx stylelint "**/*.module.css" --fix
当检测到裸全局选择器时,终端会报:
“全局选择器 'body' 请提取到 <style jsx global>”
并自动在文件末尾追加:
/* style-jsx-global */
body { margin: 0; }
- 开发者收到提示后,把这段代码剪切到 pages/_app.jsx 的 <style jsx global> 标签内即可。CI 门禁通过,MR 可合并。
拓展思考
-
规则颗粒度:
国内大仓常有“主题色覆盖”需求,允许 :root 里定义变量。此时可在 secondary 选项里加 allowRootVariables: true,通过二次校验放行,避免误杀。 -
自动修复边界:
当同一文件里既有全局又有局部样式时,直接 append 会打乱顺序,导致优先级问题。修复函数需计算原节点的“后置兄弟节点”,插入到相同上下文位置,保持层叠顺序。 -
与 RSC 结合:
Next.js 13 App Router 默认服务端组件,不支持 <style jsx global>。规则需识别 app/ 目录,自动降级提示为“请迁移到 global.css 并在 root layout 引入”,避免开发者困惑。 -
性能优化:
大仓库 2000+ 文件扫描耗时 30s+,可把规则缓存键设计为“文件路径 + 选择器哈希”,利用 Stylelint 的 cache 机制,二次扫描耗时降到 3s 以内,满足流水线 5s 门禁要求。 -
低代码场景:
阿里低代码平台允许用户在线写 CSS,规则需暴露为 WebAssembly 版本,在浏览器端实时提示,并给出“一键提取到全局样式面板”的按钮,打通设计与研发链路。