当使用 Windicss 属性模式时,如何检测未定义的工具类?

解读

  1. 国内现状:Vue3 + Vite 项目普遍采用 Windicss 属性模式(如 <div text="red-500 sm:blue-800">),工具类被写在 HTML 属性里,传统 Stylelint 只能扫描 .css/.scss/.less 文件,无法感知模板中的原子类。
  2. 考点定位:面试官想确认候选人是否理解“Stylelint 只认识 CSS AST”这一核心限制,并能否通过“自定义规则 + 提取器”把非 CSS 上下文里的类名也纳入 lint 流程。
  3. 落地难点:
    • 属性语法不是标准 CSS,需要把 text="red-500" 解析成 .text-red-500;
    • Windicss 支持动态拼接、shortcuts、variant group,类名可能不存在于静态的 utilities 清单;
    • 必须兼顾性能,不能每次 lint 都全量扫描 node_modules。

知识点

  1. PostCSS 插件执行顺序:Stylelint 运行在 PostCSS 阶段,只能看到被 PostCSS 解析的“文件”。
  2. stylelint-processor-html / @stylelint/postcss-css-in-js:官方处理器机制,可把 Vue SFC、jsx 等文件切成 <style> 与 JS 片段,但默认不识别属性模式。
  3. stylelint-selector-bem-pattern、stylelint-no-unsupported-browser-features:社区规则实现范式,可供参考“如何读取配置文件并做类名校验”。
  4. Windicss 暴露的 createUtils():运行时 API,可一次性拿到所有 utilities、shortcuts、variants 的静态列表,用于白名单比对。
  5. stylelint 自定义规则骨架:ruleFunction(primaryOption, secondaryOption, context) + utils.report(),可异步读取配置文件。
  6. 提取器(extractor)写法:正则或 AST 遍历,把 text="" bg="" border="" 等属性值拆成原子类数组。
  7. 缓存策略:把 Windicss utils 列表序列化到 .cache/windi-utils.json,mtime 未变时直接读缓存,避免每次 lint 重新扫描。
  8. 自动修复:若开启 --fix,可给出 text-red-500 → text-red-600 的替换建议,但属性模式语法下只能提示,不能直接重写模板。

答案

“分三步实现:

  1. 写自定义规则 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 })。
  2. 配置 .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' }]
    };
    
  3. 在 CI 与 VS Code 同时接入:
    • GitHub Actions 缓存 .cache/windi-utils.json,增量提速;
    • VS Code 插件 stylelint.vscode-stylelint 添加 "stylelint.validate": ["vue"],保存即触发实时提示。

这样即可在属性模式下拦截拼写错误、已废弃或误用的工具类,保证设计系统一致。”

拓展思考

  1. 动态类名:模板里 :class="btn ${type}" 这类运行时拼接无法静态穷举,可在规则里加 allowDynamic: true 选项,只校验显式写出来的原子类,降低误报。
  2. 性能优化:把 Windicss utils 列表转成 Trie 树,类名存在性查询从 O(n) 降到 O(1),单文件 2 万行组件 lint 时间 < 200 ms。
  3. 与 Tailwind 项目共用:抽象成 stylelint-plugin-atomic-css,通过 engine: 'windi' | 'tailwind' 参数切换底层引擎,提高团队多项目复用率。
  4. 自动补全:结合 VS Code Language Server,把 utils 列表作为 completion 源,实现“边写属性边提示”,把 linter 与编辑器体验打通。