🚀 前端项目代码质量配置Prettier + Commitlint + Husky + Lint-staged

一套完整的代码质量保障方案: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}

🎯 使用指南

💻 日常开发流程

  1. 编写代码:正常开发,无需担心格式问题

  2. 提交代码

    bash 复制代码
    git add .
    git commit -m "feat: 添加用户登录功能"
  3. 自动处理

    • 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 中的格式讨论
相关推荐
恋猫de小郭2 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅8 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60619 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了9 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅9 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅9 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅10 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment10 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅10 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊10 小时前
jwt介绍
前端