当使用 Windicss 属性模式时,如何检测未定义的工具类?
解读
- 国内现状:Vue3 + Vite 项目普遍采用 Windicss 属性模式(如
<div text="red-500 sm:blue-800">),工具类被写在 HTML 属性里,传统 Stylelint 只能扫描.css/.scss/.less文件,无法感知模板中的原子类。 - 考点定位:面试官想确认候选人是否理解“Stylelint 只认识 CSS AST”这一核心限制,并能否通过“自定义规则 + 提取器”把非 CSS 上下文里的类名也纳入 lint 流程。
- 落地难点:
- 属性语法不是标准 CSS,需要把
text="red-500"解析成.text-red-500; - Windicss 支持动态拼接、shortcuts、variant group,类名可能不存在于静态的 utilities 清单;
- 必须兼顾性能,不能每次 lint 都全量扫描 node_modules。
- 属性语法不是标准 CSS,需要把
知识点
- PostCSS 插件执行顺序:Stylelint 运行在 PostCSS 阶段,只能看到被 PostCSS 解析的“文件”。
- stylelint-processor-html / @stylelint/postcss-css-in-js:官方处理器机制,可把 Vue SFC、jsx 等文件切成
<style>与 JS 片段,但默认不识别属性模式。 - stylelint-selector-bem-pattern、stylelint-no-unsupported-browser-features:社区规则实现范式,可供参考“如何读取配置文件并做类名校验”。
- Windicss 暴露的
createUtils():运行时 API,可一次性拿到所有 utilities、shortcuts、variants 的静态列表,用于白名单比对。 - stylelint 自定义规则骨架:
ruleFunction(primaryOption, secondaryOption, context)+utils.report(),可异步读取配置文件。 - 提取器(extractor)写法:正则或 AST 遍历,把
text=""bg=""border=""等属性值拆成原子类数组。 - 缓存策略:把 Windicss utils 列表序列化到
.cache/windi-utils.json,mtime 未变时直接读缓存,避免每次 lint 重新扫描。 - 自动修复:若开启
--fix,可给出text-red-500→text-red-600的替换建议,但属性模式语法下只能提示,不能直接重写模板。
答案
“分三步实现:
- 写自定义规则
stylelint-plugin-windi-attribute:
a. 在index.js里注册windi-attribute-no-unknown规则;
b. 规则初始化阶段调用createUtils({ config: 'windi.config.ts' })拿到完整 utilities 白名单并缓存;
c. 利用postcss-plugin钩子,对每一个Root节点,如果是.vue或.jsx文件,走自定义提取器把属性值拆成类名数组;
d. 遍历类名,若不在白名单且不属于正则/^(\!|\-)?([a-z0-9\-:]+)$/的动态拼接,就utils.report({ message:Unknown Windi utility "${cls}", node })。 - 配置
.stylelintrc.js:module.exports = { plugins: ['./lib/stylelint-plugin-windi-attribute'], rules: { 'plugin/windi-attribute-no-unknown': [true, { severity: 'error' }] }, overrides: [{ files: ['*.vue', '*.tsx'], customSyntax: 'postcss-html' }] }; - 在 CI 与 VS Code 同时接入:
- GitHub Actions 缓存
.cache/windi-utils.json,增量提速; - VS Code 插件
stylelint.vscode-stylelint添加"stylelint.validate": ["vue"],保存即触发实时提示。
- GitHub Actions 缓存
这样即可在属性模式下拦截拼写错误、已废弃或误用的工具类,保证设计系统一致。”
拓展思考
- 动态类名:模板里
:class="btn ${type}"这类运行时拼接无法静态穷举,可在规则里加allowDynamic: true选项,只校验显式写出来的原子类,降低误报。 - 性能优化:把 Windicss utils 列表转成 Trie 树,类名存在性查询从 O(n) 降到 O(1),单文件 2 万行组件 lint 时间 < 200 ms。
- 与 Tailwind 项目共用:抽象成
stylelint-plugin-atomic-css,通过engine: 'windi' | 'tailwind'参数切换底层引擎,提高团队多项目复用率。 - 自动补全:结合 VS Code Language Server,把 utils 列表作为 completion 源,实现“边写属性边提示”,把 linter 与编辑器体验打通。