一套完整的代码质量保障方案:Prettier + Commitlint + Husky + Lint-staged,让你的项目告别代码风格争论!
✨ 为什么需要这套配置?
- 🎨 统一代码风格:告别团队成员间的代码格式争论
- 🔒 强制规范检查:提交前自动检查,确保代码质量
- 📝 规范提交信息:标准化 Git 提交信息,便于版本管理
- ⚡ 高效检查:只检查待提交的文件,提升检查速度
- 🛠️ 零配置上手:复制粘贴即可使用,开箱即用
🏗️ 工具架构
graph LR
A[代码提交] --> B[Husky pre-commit]
B --> C[Lint-staged]
C --> D[ESLint 检查]
C --> E[Prettier 格式化]
D --> F[commit-msg 钩子]
E --> F
F --> G[Commitlint 检查]
G --> H[提交成功]
📦 快速开始
1. 安装依赖
bash
# 使用 npm
npm install -D prettier @commitlint/cli @commitlint/config-conventional husky lint-staged
# 使用 pnpm
pnpm add -D prettier @commitlint/cli @commitlint/config-conventional husky lint-staged
# 使用 yarn
yarn add -D prettier @commitlint/cli @commitlint/config-conventional husky lint-staged
2. 初始化 Husky
bash
# 初始化 husky
npx husky init
# 或者在 package.json 中添加 prepare 脚本
npm pkg set scripts.prepare="husky"
npm run prepare
3. 复制配置文件
将以下配置文件复制到你的项目根目录:
⚙️ 配置文件详解
📄 package.json
在 package.json
中添加以下配置:
json
{
"scripts": {
"prepare": "husky"
},
"lint-staged": {
"*.{js,jsx,ts,tsx,vue}": ["eslint --fix", "prettier --write"],
"*.{json,md,yml,yaml}": ["prettier --write"]
}
}
🎨 .prettierrc.mjs
javascript
/**
* Prettier 配置文件
* 代码格式化规则配置
*/
export default {
printWidth: 100, // 每行最大字符数
tabWidth: 2, // 缩进空格数
useTabs: false, // 使用空格而不是制表符
semi: true, // 语句末尾添加分号
singleQuote: true, // 使用单引号
quoteProps: 'as-needed', // 对象属性仅在需要时添加引号
bracketSpacing: true, // 对象大括号内添加空格
bracketSameLine: false, // HTML 标签的 > 换行显示
arrowParens: 'avoid', // 箭头函数参数使用括号
endOfLine: 'lf', // 使用 Unix 换行符
trailingComma: 'none', // 不添加尾随逗号
vueIndentScriptAndStyle: false, // Vue 文件 script/style 不额外缩进
singleAttributePerLine: false, // HTML 属性不强制每行一个
htmlWhitespaceSensitivity: 'css', // HTML 空格敏感度
embeddedLanguageFormatting: 'auto' // 自动格式化嵌入代码
};
🚫 .prettierignore
text
# Lock files
package-lock.json
pnpm-lock.yaml
yarn.lock
# Build outputs
dist/
build/
.turbo/
.nuxt/
# Dependencies
node_modules/
# Generated files
*.d.ts
coverage/
.nyc_output/
# IDE and OS files
.DS_Store
.vscode/settings.json
.idea/
# Log files
*.log
logs/
# Temporary files
tmp/
temp/
💬 commitlint.config.mjs
javascript
/**
* Commitlint 配置文件
* Git 提交信息规范检查
*/
export default {
extends: ['@commitlint/config-conventional'],
rules: {
// 限制主题最大长度为 72(推荐范围)
'subject-max-length': [2, 'always', 72],
// 类型必须是下列之一
'type-enum': [
2,
'always',
[
'feat', // 新功能
'fix', // 修复 bug
'docs', // 文档改动
'style', // 代码格式(不影响功能)
'refactor', // 代码重构
'perf', // 性能优化
'test', // 添加测试
'build', // 构建相关
'ci', // CI 配置
'chore', // 杂项(依赖更新等)
'revert' // 回滚
]
],
// 提交 message 必须以小写字母开头
'subject-case': [2, 'never', ['start-case', 'pascal-case', 'upper-case']]
}
};
🪝 Husky 钩子配置
创建 .husky/pre-commit
文件:
bash
npx lint-staged
创建 .husky/commit-msg
文件:
bash
npx --no -- commitlint --edit ${1}
🎯 使用指南
💻 日常开发流程
-
编写代码:正常开发,无需担心格式问题
-
提交代码 :
bashgit add . git commit -m "feat: 添加用户登录功能"
-
自动处理 :
- pre-commit 钩子自动格式化代码
- commit-msg 钩子检查提交信息格式
- 检查通过后完成提交
✅ 提交信息规范
提交信息格式:<type>(<scope>): <subject>
常用类型说明:
类型 | 说明 | 示例 |
---|---|---|
feat |
新功能 | feat: 添加用户登录功能 |
fix |
修复 bug | fix: 修复用户头像显示问题 |
docs |
文档更新 | docs: 更新 API 文档 |
style |
代码格式调整 | style: 格式化代码 |
refactor |
代码重构 | refactor: 重构用户模块 |
test |
添加测试 | test: 添加登录功能测试 |
chore |
构建/工具变动 | chore: 更新依赖版本 |
🔧 手动执行命令
bash
# 格式化所有文件
npx prettier --write .
# 检查提交信息
echo "feat: 测试提交" | npx commitlint
# 手动执行 lint-staged
npx lint-staged
🎨 自定义配置
修改 Prettier 规则
编辑 .prettierrc.mjs
文件,常用自定义选项:
javascript
export default {
printWidth: 120, // 调整行宽
singleQuote: false, // 改用双引号
trailingComma: 'es5' // 添加尾随逗号
// ... 其他配置
};
修改 Commitlint 规则
编辑 commitlint.config.mjs
文件:
javascript
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'subject-max-length': [2, 'always', 50], // 调整主题长度
'type-enum': [2, 'always', ['feat', 'fix', 'docs']] // 限制提交类型
}
};
修改 Lint-staged 规则
在 package.json
中调整:
json
{
"lint-staged": {
"*.{js,ts}": ["eslint --fix", "prettier --write"],
"*.css": ["stylelint --fix", "prettier --write"],
"*.md": ["prettier --write"]
}
}
🚨 常见问题
Q: 提交时报错 "husky command not found"
A: 确保已经运行 npm run prepare
初始化 husky
Q: Prettier 格式化与 ESLint 冲突
A: 安装 eslint-config-prettier
禁用 ESLint 中与 Prettier 冲突的规则
Q: 想跳过钩子检查
A: 使用 --no-verify
参数:
bash
git commit -m "紧急修复" --no-verify
Q: 批量格式化现有代码
A: 运行格式化命令:
bash
npx prettier --write .
📚 进阶配置
集成到 VS Code
在 .vscode/settings.json
中添加:
json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
🎉 总结
这套配置可以帮助你的团队:
- ✅ 保持一致的代码风格
- ✅ 规范化提交信息
- ✅ 自动化代码质量检查
- ✅ 提升开发效率
- ✅ 减少 Code Review 中的格式讨论