htmlhint 比 eslint + html-eslint 更适合构建阶段检查,因其专为 html 设计、规则细粒度、开箱即用、不依赖 js 运行时解析,能稳定支持纯 html 文件和各类构建工具。

HTMLHint 为什么比 ESLint + html-eslint 更适合构建阶段检查
HTMLHint 是专为 HTML 设计的静态分析器,规则粒度细、开箱即用、不依赖 JS 运行时解析。而 html-eslint 实际是 ESLint 的插件层封装,本质仍走 JS AST 解析路径,对纯 HTML 文件(如模板片段、独立 .html 页面)支持不稳定,尤其在 Vite 或 Rollup 的非 JS 入口场景下常报 ParseError: Unexpected token 或跳过检查。
常见错误现象:在 Vite 项目中配置 eslint-plugin-html 后,vite build 能跑过,但 npm run lint 却漏检 <div class="foo"> 这类大写属性 —— 因为 ESLint 默认只处理 <code>.js 和 .jsx,需额外配 overrides 才能识别 .html,且无法覆盖 doctype-first、attr-lowercase 等 HTML 语义规则。
- HTMLHint 内置
doctype-first、meta-charset-require、tagname-lowercase等 40+ 条 HTML 专属规则,直接命中 W3C 规范 - 它不解析 JS 逻辑,不关心
innerHTML拼接,专注标签结构、属性拼写、编码声明等静态层面 - Vite/Rollup/webpack 插件(如
vite-plugin-htmlhint)可无缝注入构建流程,在build阶段失败而非仅开发时提示
Vite 中启用 HTMLHint 的最小可行配置
不要在 vite.config.ts 里写一堆插件链式调用。Vite 生态已有轻量封装,推荐直接用 vite-plugin-htmlhint,它会在 build 和 serve 阶段自动扫描入口 HTML 及所有被 import 的模板文件(如 import './index.html')。
安装与配置步骤:
- 运行
npm install vite-plugin-htmlhint --save-dev - 在
vite.config.ts中添加插件:import htmlhint from 'vite-plugin-htmlhint'<br>export default defineConfig({<br> plugins: [<br> htmlhint({<br> rules: {<br> 'doctype-first': true,<br> 'tagname-lowercase': true,<br> 'attr-lowercase': true,<br> 'attr-quote': 'double'<br> }<br> })<br> ]<br>}) - 确保项目根目录有
.htmlhintrc(JSON 格式),内容与插件内 rules 合并生效;若两者冲突,以插件内配置为准
注意:该插件默认只检查 index.html 和通过 import 显式引入的 HTML 文件。若你用的是 vite-plugin-html 动态注入模板,需手动在插件 options 中加 include: ['src/**/*.html']。
Webpack 构建中 HTMLHint 的执行时机陷阱
Webpack 本身不处理 HTML lint,必须靠 loader 或 plugin 注入。常见错误是把 HTMLHint 当作 html-webpack-plugin 的子配置塞进去,结果发现构建完全不报错 —— 因为 html-webpack-plugin 只负责生成 HTML,不触发 lint。
正确做法是用 htmlhint-loader,但它必须放在 html-webpack-plugin 之前,且仅对 require('./template.html') 这类显式引入生效,对 template: './index.html' 这种配置无效。
- 在
webpack.config.js的module.rules中添加:{<br> test: /\.html$/,<br> exclude: /node_modules/,<br> use: [<br> {<br> loader: 'htmlhint-loader',<br> options: {<br> rules: { 'attr-lowercase': true }<br> }<br> }<br> ]<br>} - 如果使用
html-webpack-plugin的template选项,需额外加htmlhint-webpack-plugin,并在plugins数组中声明,否则 template 文件永远不被检查 - CI 环境中建议用 CLI 方式兜底:
npx htmlhint src/index.html src/templates/*.html,避免 loader 配置遗漏
Rollup + HTMLHint 的兼容性短板
Rollup 官方生态缺乏成熟 HTMLHint 插件,社区方案(如 rollup-plugin-htmlhint)大多已归档或年久未维护。直接用 CLI 在 build 脚本里调用最稳,但要注意路径解析问题。
典型错误:在 package.json 的 build 脚本里写 "build": "rollup -c && htmlhint src/**/*.html",结果 CI 报错 Cannot find module 'src/index.html' —— 因为 htmlhint 默认从当前工作目录开始解析 glob,而 Rollup 可能已切换到 dist 目录。
- 固定工作目录:改用
cd src && htmlhint **/*.html或指定--config和--cwd - 避免 glob 膨胀:Rollup 构建前通常只产出少量 HTML(如 SPA 入口),建议显式列出文件:
htmlhint index.html admin.html - 若用
@rollup/plugin-html处理模板,它不触发 lint,必须单独加 CLI 步骤,且不能依赖插件返回值中断构建 —— 需用set -e(bash)或|| exit 1(cross-env)保证失败退出
真正容易被忽略的点:HTMLHint 的 attr-value-double-quotes 规则默认只检查双引号,但 Vue/Svelte 模板中常出现 :class="{ active: isAct }" 这类绑定语法,会被误判为属性值未引号 —— 此时必须关掉该规则,或换用更语义化的校验工具(如专门针对框架模板的 eslint-plugin-vue)。纯 HTML 流水线里,别让它越界管 JS 表达式。











