tidy 是最稳定、零依赖的 html 格式化工具,支持直接覆盖原文件或输出到新文件;需用 tidy-html5 5.4+ 版本以启用 --indent-attributes yes 实现属性垂直对齐,并配合 -w 140 避免 integrity 哈希折行。

用 tidy 命令格式化 HTML 并写入文件
直接覆盖原文件或输出到新文件,tidy 是最稳定、零依赖的选择。它不依赖 Node.js 或 Python 环境,适合 CI/CD、服务器批量处理或老旧系统。
-
tidy -i -m input.html:启用缩进(-i)并直接修改原文件(-m),适合本地快速修整 -
tidy -i -ashtml -o output.html input.html:保持原文件不变,格式化后另存为output.html;-ashtml强制输出为标准 HTML(避免被识别为 XHTML) - 若报错
line X column Y: missing ,加 <code>--doctype html可静默修复,无需手动补全 - 旧版
tidy(如 Windows 自带的 2009 年版)不支持-ashtml或--indent-attributes,建议用tidy-html5(通过brew install tidy-html5或apt install tidy安装)
让 link 和 script 的多属性垂直对齐
默认 tidy -i 只缩进标签层级,属性仍挤在一行——这对含 integrity、crossorigin、href 的现代资源标签极不友好。
- 必须使用
--indent-attributes yes(Tidy 5.4+ 才支持),例如:tidy -i --indent-attributes yes -w 140 input.html -o formatted.html -
-w 140控制行宽:设太小(如-w 80)会导致integrity哈希值被硬折行,破坏完整性校验;设太大(如-w 200)则失去对齐意义 - 该选项对
<meta>、<img>同样生效,但不会影响<script></script>标签内部的 JS 代码(Tidy 默认不解析 script 内容) - 若发现属性没换行,先运行
tidy -v确认版本 ≥ 5.6.0;低于此版本需升级,不可绕过
用 prettier 替代时要注意编码和平台差异
prettier 对 HTML 支持好、配置灵活,但在 Windows 上容易因编码问题输出乱码,不是“装完就能用”。
- 确保源文件是 UTF-8 编码(用 VS Code 或 Notepad++ 检查“文件 → 编码”),否则
prettier --write可能损坏中文或符号 - Windows CMD 中执行前,务必先运行
chcp 65001切换代码页,否则控制台输出会乱码 - 推荐命令:
prettier --write --parser html --tab-width 2 --print-width 100 *.html;其中--parser html显式指定解析器,避免误判为 JSX - 若项目中混用 Pug 或 Vue SFC,
prettier可能误格式化模板块,此时应退回tidy或加--ignore-path .prettierignore
临时生成带缩进的 HTML 文件别用 echo
echo 适合单行原型,但多行 HTML 容易因 shell 解析丢失换行或转义字符,可读性差且难维护。
- 改用
printf:它原生支持多行字符串和精确缩进,例如:printf '\n\n \n <title>Test</title>\n \n' > test.html - 如果内容含变量或需复用,用 shell here-document 更可靠:
cat > page.html \n\n<title>Dynamic</title>\n\nEOF - 注意:
echo在不同 shell(bash/zsh/PowerShell)中对反斜杠处理不一致,printf行为统一,是跨平台生成脚本的底线选择
tidy 的 --indent-attributes yes 是唯一能稳定解决多属性垂直对齐的方案,而它的版本兼容性陷阱最容易被忽略——不是所有叫 tidy 的命令都支持这个参数。前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











