如何校验子应用卸载时清理动态插入的 <style>?
解读
在国内微前端落地场景中,子应用(尤其是 qiankun、micro-app、wujie 等框架里的子应用)经常通过 document.head.appendChild(style) 或 import('./xxx.css') 的方式把样式动态注入到基座。子应用卸载时如果忘记把对应的 <style> 标签移除,会导致:
- 样式残留污染其他子应用;
- 内存泄漏,节点与样式表对象无法 GC;
- 白屏或样式错乱,用户投诉。
因此,面试官想通过“Stylelint 能否、如何发现这类隐患”考察三点:
- 是否理解 Stylelint 只能做「静态 AST 分析」;
- 能否把「运行时清理」问题转化为「静态可识别模式」;
- 是否熟悉 PostCSS AST 节点类型及 Stylelint 插件开发套路。
知识点
- Stylelint 插件体系:基于
postcss的RootAST,遍历rule、atRule、decl等节点;通过stylelint.utils.report上报错误。 - 动态插入样式的常见写法:
const style = document.createElement('style')…head.appendChild(style);new CSSStyleSheet()…adoptedStyleSheets.push();- 微前端框架自动封装,如
__webpack_public_path__ + 'main.css'。
- 清理逻辑的常见写法:
style.parentNode.removeChild(style);adoptedStyleSheets = adoptedStyleSheets.filter(x => x !== sheet);- 生命周期函数
unmount/beforeUnmount中执行。
- 静态识别思路:
- 先找到“插入”语句,再检查同一作用域或同一文件内是否存在“卸载”语句;
- 若找不到,则报
no-cleanup-dynamic-style警告。
- 技术限制:
- 跨文件分析需借助 ESLint 或 TypeScript Language Service,Stylelint 单文件内最稳;
- 运行时代码可能经过打包压缩,AST 中变量名被混淆,需做作用域追踪(
scope-manager或eslint-scope逻辑简化版)。
答案
“Stylelint 本身只做静态分析,不能直接感知运行时 DOM 状态,但可以通过自定义规则把『出现插入语句却找不到对应清理语句』识别为可疑模式。具体做法分三步:
第一步,在 .stylelintrc.js 里注册本地插件:
module.exports = {
plugins: ['./lib/rules/no-missing-style-cleanup'],
rules: { 'plugin/no-missing-style-cleanup': true }
};
第二步,实现插件 no-missing-style-cleanup.js:
const stylelint = require('stylelint');
const { utils } = stylelint;
const ruleName = 'plugin/no-missing-style-cleanup';
const insertRegex = /\b(head|body)\.appendChild\(\s*style\s*\)/;
const cleanupRegex = /\bstyle\.parentNode\.removeChild\(\s*style\s*\)/;
const rule = primaryOption => (root, result) => {
if (!primaryOption) return;
let hasInsert = false;
let hasCleanup = false;
root.walkRules(() => {}); // 触发一次完整遍历,保证注释也在 AST 中
root.source.input.css.split('\n').forEach((line, idx) => {
if (insertRegex.test(line)) hasInsert = true;
if (cleanupRegex.test(line)) hasCleanup = true;
});
if (hasInsert && !hasCleanup) {
utils.report({
message: '动态插入的 <style> 未在卸载时清理,可能导致样式残留',
node: root,
result,
ruleName,
line: 1
});
}
};
rule.ruleName = ruleName;
rule.messages = utils.ruleMessages(ruleName, {});
module.exports = stylelint.createPlugin(ruleName, rule);
第三步,把该规则纳入 CI:
# .github/workflows/lint.yml
- run: npx stylelint 'src/**/*.js'
若子应用源码里写了 appendChild(style) 却找不到对称的 removeChild,流水线就会失败,强制开发者补充卸载逻辑。
补充:如果项目用 TypeScript 且样式插入封装在 .ts 文件,可把相同逻辑写成 ESLint 规则;Stylelint 侧只负责『出现行内 <style> 标签但无 data-micro-app-name 属性』这类静态标记,二者互补。”
拓展思考
- 微前端框架层面能否统一收集样式表?
qiankun 的sandbox在unmount阶段可自动遍历document.head把带qiankun-前缀的<style>移除;Stylelint 规则可强制要求动态插入的<style>必须带约定属性,如style.setAttribute('data-sub-app', 'order'),否则报错。 - 如何降低误报?
变量名混淆场景下,可用scope.analysis追踪style标识符是否真正指向createElement('style');亦可在规则里加白名单注释/* stylelint-disable-next-line no-missing-style-cleanup */。 - 性能与增量扫描:
大仓库可结合stylelint --cache与nx affected:lint,只让发生变更的子应用走这条规则,节省 CI 时间。 - 与单元测试互补:
Stylelint 保证“代码写了清理”,Jest +@testing-library/dom可写快照测试验证“卸载后 DOM 里确实没有残留<style>”,形成静态 + 运行时双保险。