本文目录导读:

- 通用格式化工具
- Python - autopep8
- JavaScript/TypeScript - ESLint
- Shell脚本批量处理
- 跨语言工具比较
- Git Hooks 自动格式化
- VS Code 集成
- 批处理脚本示例
- 推荐方案
通用格式化工具
Prettier(最推荐 - 支持多语言)
# 安装
npm install -g prettier
# 格式化所有文件
prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,md}"
# 检查但不修改
prettier --check "src/**/*.{js,jsx,ts,tsx,json,css,md}"
配置文件 .prettierrc:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
Python - autopep8
# 安装
pip install autopep8
# 格式化所有Python文件
find . -name "*.py" -exec autopep8 --in-place {} \;
# 或
autopep8 --recursive --in-place .
JavaScript/TypeScript - ESLint
# 安装
npm install -g eslint
# 自动修复
eslint --fix "src/**/*.{js,jsx,ts,tsx}"
配置文件 .eslintrc.json:
{
"extends": "eslint:recommended",
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "single"]
}
}
Shell脚本批量处理
创建一个 format-all.sh:
#!/bin/bash
# 批量格式化脚本
# 配置
SRC_DIR="./src"
EXCLUDE_DIRS=("node_modules" "dist" ".git")
# 检测文件类型并格式化
format_file() {
local file=$1
case "${file##*.}" in
js|jsx|ts|tsx|json|css|md)
prettier --write "$file"
;;
py)
autopep8 --in-place "$file"
;;
c|cpp|h|hpp)
clang-format -i "$file"
;;
*)
echo "跳过: $file"
;;
esac
}
# 递归处理
find "$SRC_DIR" -type f | while read file; do
# 排除目录
for exclude in "${EXCLUDE_DIRS[@]}"; do
if [[ "$file" == *"$exclude"* ]]; then
continue 2
fi
done
format_file "$file"
done
echo "格式化完成!"
跨语言工具比较
| 工具 | 支持语言 | 安装方式 | 特点 |
|---|---|---|---|
| Prettier | JS, TS, CSS, JSON, Markdown, YAML | npm | 配置少,效果统一 |
| Black | Python | pip | 零配置,强制规范 |
| clang-format | C/C++, Java, JS | apt/brew | 可定制性强 |
| gofmt | Go | go install | 官方标准 |
| rustfmt | Rust | rustup | 官方标准 |
Git Hooks 自动格式化
创建 .husky/pre-commit:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# 只格式化改动的文件
git diff --cached --name-only --diff-filter=ACM | while read file; do
case "${file##*.}" in
js|jsx|ts|tsx|json|css|md)
npx prettier --write "$file"
git add "$file"
;;
esac
done
VS Code 集成
配置 settings.json:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
},
"[cpp]": {
"editor.defaultFormatter": "xaver.clang-format"
}
}
批处理脚本示例
Windows PowerShell:
# 格式化所有JS/TS文件
Get-ChildItem -Path .\src -Recurse -Include *.js,*.ts,*.jsx,*.tsx |
Where-Object { $_.DirectoryName -notmatch 'node_modules|dist' } |
ForEach-Object { npx prettier --write $_.FullName }
macOS/Linux:
# 一键格式化
find . -type f \( -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" -o -name "*.css" -o -name "*.json" \) \
-not -path "./node_modules/*" \
-not -path "./dist/*" \
-exec prettier --write {} \;
推荐方案
对于大多数项目,推荐使用:
- Prettier(前端项目)
- Black(Python项目)
- ESLint + Prettier(严格规范)
先在单个文件测试,确认效果后再批量运行,记得先提交或备份代码!