应使用html-minifier-terser而非已停更的老版html-minifier,因其基于Terser引擎,能安全处理现代HTML5语法、模板字符串及ES2020+特性;Webpack中通过html-webpack-plugin配置时需谨慎启用removeScriptTypeAttributes和minifyJS等选项,避免破坏模块加载或调试信息。
直接用 html-minifier-terser,别碰老版 html-minifier —— 它已停止维护,对现代 HTML(比如含 <template>、<slot>、ES2020+ 内联脚本)支持不稳定,容易误删或报错。
本地开发或构建流程中压缩 HTML,必须装 html-minifier-terser:
npm install --save-dev html-minifier-terserhtml-minifier 的 minifyJS: true 在遇到 `${x}` 或 a?.b 时会直接抛 SyntaxError
html-minifier-terser,不用手动引入不是所有选项都适合开,尤其在含服务端渲染或模板语法的项目里:
removeComments: true 会删掉 <!-- htmlmin:ignore --> 外的所有注释,但 EJS/Nunjucks 占位符如 <%= title %> 不是注释,不会被删 —— 前提是没配 ignoreCustomComments 错误正则removeScriptTypeAttributes: true 会删 <script type="module"> 里的 type,导致模块加载失败;只建议对 type="text/javascript" 生效minifyJS: true 和 Webpack 自带的 terser-webpack-plugin 双重压缩 JS,可能把 console.log 残留变量名压缩掉,引发调试困难;生产环境建议设为 { compress: false } 或干脆关掉new HtmlWebpackPlugin({ minify: { collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeScriptTypeAttributes: false, // 手动控制 minifyJS: { compress: false } }})
CLI 默认把 <svg> 当普通标签处理,可能错误移除 viewBox 空格或闭合斜杠,导致渲染异常:
立即学习“前端免费学习笔记(深入)”;
--custom-element-prefixes svg(v6+ 支持),让解析器识别 SVG 元素并跳过属性精简<my-button>),需加 --custom-element-prefixes my-,否则 removeRedundantAttributes 可能删掉必需的属性--remove-optional-tags 压缩含 <math> 或 <foreignObject> 的页面,这些标签的闭合规则和 HTML 不同,强制移除 </math> 会破坏结构html-minifier --collapse-whitespace --remove-comments --custom-element-prefixes svg,my- input.html -o output.html
最易被忽略的一点:HTML 压缩只是传输层优化的第一步,gzip 或 brotli 开启后,removeComments 带来的体积收益可能只剩 1–2%,而误删 data-* 属性或破坏内联 JSON 结构的风险却真实存在。上线前务必用 diff 对比压缩前后 DOM 快照,别只看文件大小。