跳转到内容

Prettier 代码格式化与 Commit 规范完全指南 | 提升团队协作效率

Code Formatting and Commit Standards

在团队协作开发中,代码风格一致性提交信息规范性是保证项目可维护性的关键。Prettier 是最流行的代码格式化工具,而 Conventional Commits 规范则让提交历史清晰可读。本文将详细介绍如何为项目配置完整的代码质量和提交规范体系。

为什么需要代码格式化和 Commit 规范?

核心痛点

问题影响解决方案
🎨 代码风格不统一阅读困难,合并冲突多Prettier 自动格式化
📝 提交信息混乱无法追溯变更原因Conventional Commits
🔍 Code Review 低效浪费时间检查格式自动化检查
🚀 发布日志难生成手动整理耗时规范化自动生成
🤝 团队协作成本高新人上手慢统一规范降低门槛

带来的价值

提升代码质量:统一的代码风格,减少低级错误 ✅ 提高协作效率:清晰的提交历史,便于追溯和回滚 ✅ 自动化工作流:CI/CD 自动校验,减少人工干预 ✅ 专业形象:规范的开源项目更容易获得信任 ✅ 长期可维护:标准化的代码库更易维护和扩展

1. 配置 Prettier 格式化代码

安装 Prettier 及相关插件

shell
pnpm add --save-dev --save-exact prettier @trivago/prettier-plugin-sort-imports prettier-plugin-jsdoc prettier-plugin-packagejson prettier-plugin-sort-json
shell
npm install --save-dev --save-exact prettier @trivago/prettier-plugin-sort-imports prettier-plugin-jsdoc prettier-plugin-packagejson prettier-plugin-sort-json
shell
yarn add --dev --exact prettier @trivago/prettier-plugin-sort-imports prettier-plugin-jsdoc prettier-plugin-packagejson prettier-plugin-sort-json

插件功能说明

插件功能必要性
prettier核心格式化工具✅ 必装
@trivago/prettier-plugin-sort-imports自动排序 import 语句⭐ 推荐
prettier-plugin-jsdoc格式化 JSDoc 注释⭐ 推荐
prettier-plugin-packagejson格式化 package.json⭐ 推荐
prettier-plugin-sort-json排序 JSON 文件键名可选

安装注意事项:

bash
# --save-exact 锁定精确版本,避免团队环境不一致
# --save-dev 仅作为开发依赖

# 验证安装
npx prettier --version

Prettier 配置

新建 .prettierrc.yaml 配置如下

.prettierrc.yaml
yaml
plugins:
  - '@trivago/prettier-plugin-sort-imports'
  - 'prettier-plugin-packagejson'
  - 'prettier-plugin-sort-json'
  - 'prettier-plugin-vitepress'

printWidth: 120
semi: false
singleQuote: true
trailingComma: 'none'

importOrderSeparation: false
importOrderSortSpecifiers: true
importOrder:
  - '<THIRD_PARTY_MODULES>'
  - '^vitepress$'
  - '^vitepress([-/].*)?$'
  - '^vue$'
  - '^vite$'
  - '^@[a-zA-Z0-9-]+/(.*)$'
  - '^@/(.*)$'
  - '^./.*$'
  - '^../.*$'
  - '^[./]'
  - '^(.*)$'

overrides:
  - files: ['*.json']
    options:
      jsonRecursiveSort: true

常用配置项详解

yaml
# .prettierrc.yaml

# 每行最大字符数
printWidth: 80

# 缩进空格数
tabWidth: 2

# 使用空格而非 Tab
useTabs: false

# 语句末尾加分号
semi: true

# 使用单引号
singleQuote: true

# JSX 中使用单引号
jsxSingleQuote: false

# 对象属性引号(as-needed: 必要时添加)
quoteProps: 'as-needed'

# 尾随逗号(es5: ES5 支持的位置添加)
trailingComma: 'es5'

# 对象括号间加空格
bracketSpacing: true

# JSX 尖括号不换行
bracketSameLine: false

# 箭头函数单个参数不加括号
arrowParens: 'avoid'

# HTML/Vue/Angular 敏感空格处理
htmlWhitespaceSensitivity: 'css'

# Vue 文件中脚本和样式标签缩进
vueIndentScriptAndStyle: false

# 换行符(lf: Unix, crlf: Windows)
endOfLine: 'lf'

# 是否格式化嵌入的代码(如 Markdown 中的代码块)
embeddedLanguageFormatting: 'auto'

# HTML、Vue、JSX 每行属性数
singleAttributePerLine: false

针对不同语言的配置:

yaml
# .prettierrc.yaml

# TypeScript 特定配置
overrides:
  - files: '*.ts'
    options:
      parser: typescript
      printWidth: 100

  - files: '*.md'
    options:
      parser: markdown
      proseWrap: 'always'

  - files: '*.json'
    options:
      parser: json
      tabWidth: 2

创建 Prettier 忽略文件

新建 .prettierignore 配置如下

.prettierignore
md
dist
pnpm-lock.yaml
cache
temp
.temp
*.vue

常见忽略规则

gitignore
# 依赖目录
node_modules/
.pnp
.pnp.js

# 构建输出
dist/
build/
.out/
coverage/

# 日志文件
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# 编辑器配置
.vscode/
.idea/
*.swp
*.swo
*~

# 系统文件
.DS_Store
Thumbs.db

# 环境变量
.env
.env.local
.env.*.local

# 锁文件(可选,根据团队约定)
# pnpm-lock.yaml
# package-lock.json
# yarn.lock

# 大型数据文件
*.min.js
*.bundle.js
*.map

# 文档生成的文件
docs/.vitepress/cache/
.vitepress/dist/

使用 Prettier 格式化所有文件

shell
pnpm exec prettier . --write
shell
npx prettier . --write
shell
yarn prettier . --write

常用命令选项

bash
# 格式化并写入
prettier --write .

# 仅检查不修改(用于 CI)
prettier --check .

# 格式化特定文件类型
prettier --write "**/*.{js,ts,jsx,tsx,json,css,md}"

# 显示帮助信息
prettier --help

# 查看配置解析结果
prettier --find-config-path .prettierrc.yaml

批量格式化示例:

bash
# 格式化 src 目录下所有 TypeScript 文件
prettier --write "src/**/*.{ts,tsx}"

# 格式化所有 Markdown 文件
prettier --write "**/*.md"

# 排除特定目录
prettier --write . --ignore-path .prettierignore

配置 commit 自动格式化

安装 simple-git-hooks 和 lint-staged 插件

zsh
pnpm install simple-git-hooks lint-staged

工具说明:

  • simple-git-hooks: 轻量级 Git hooks 管理工具
  • lint-staged: 仅对暂存文件运行 linters,提升性能

配置 package.json 示例

json
{
  "lint-staged": {
    "*": ["prettier --write --ignore-unknown"]
  },
  "simple-git-hooks": {
    "pre-commit": "pnpm lint-staged"
  }
}

安装 Git Hooks:

bash
# 初始化 hooks
npx simple-git-hooks

# 验证安装
ls -la .husky/  # 或 .git/hooks/

更精细的配置

json
{
  "lint-staged": {
    "*.{js,ts,jsx,tsx}": [
      "prettier --write",
      "eslint --fix"
    ],
    "*.{json,md,yml,yaml}": [
      "prettier --write"
    ],
    "*.css": [
      "prettier --write",
      "stylelint --fix"
    ]
  }
}

优势:

  • ✅ 不同类型文件使用不同工具
  • ✅ 并行执行,速度更快
  • ✅ 仅处理暂存文件,不影响未提交代码

2. 安装 cz-vinyl 和 commitizen 并配置

shell
pnpm add --save-dev cz-vinyl commitizen
# 或者本地全局安装
pnpm add -g cz-vinyl commitizen
shell
npm install --save-dev cz-vinyl commitizen
# 或者本地全局安装
npm install -g cz-vinyl commitizen
shell
yarn add --dev cz-vinyl commitizen
# 或者本地全局安装
yarn global add cz-vinyl commitizen
查看本地全局安装配置
  1. 在用户主目录创建 .czrc 配置文件,指定适配器路径
sh
echo '{ "path": "cz-vinyl" }' > ~/.czrc
  1. cz 命令设置别名,指向 git-cz(cz-vinyl 的执行命令):
sh
echo 'alias cz="git-cz"' >> ~/.zshrc
source ~/.zshrc

这样你可以直接通过 cz 命令启动交互式提交

Commitizen 是什么?

Commitizen 是一个命令行工具,通过交互式问答引导你创建符合 Conventional Commits 规范的提交信息。

Conventional Commits 规范:

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

示例:

feat(auth): add JWT token refresh mechanism

- Implement automatic token refresh before expiration
- Add refresh token rotation for security
- Update user session on successful refresh

Closes #123

配置 package.json 示例

json
{
  "config": {
    "commitizen": {
      "path": "cz-vinyl"
    }
  },
  "scripts": {
    "cz": "git-cz"
  }
}

使用方法:

bash
# 通过 npm script
npm run cz

# 或直接使用
npx git-cz

# 如果配置了别名
cz

cz-vinyl 选项配置示例

czvinyl.config.ts
ts
import type { CzVinylConfig } from 'cz-vinyl'

const config: CzVinylConfig = {
  headerFormat: '{type}{scope}: {subject}',
  bodyFormat: '{body}',
  commitTypes: [
    { value: 'feat', description: '新增功能' },
    { value: 'fix', description: '修复缺陷' },
    { value: 'docs', description: '文档更新' },
    { value: 'style', description: '代码格式(不影响功能,例如空格、分号等)' },
    {
      value: 'refactor',
      description: '重构代码(既不是新增功能,也不是修复 bug)'
    },
    { value: 'perf', description: '性能优化' },
    { value: 'test', description: '增加测试' },
    { value: 'chore', description: '构建过程或辅助工具变动' }
  ],
  maxCommitLineWidth: 72,
  typeQuestion: '请选择提交类型:',
  scopeQuestion: '请选择修改范围(可选):',
  skipScope: false,
  scopes: ['', 'types', 'hooks', 'utils', 'components', 'views', 'store'],
  ticketIdQuestion: '请输入关联的任务号(可选):',
  skipTicketId: true,
  subjectQuestion: '请简要描述提交内容(必填):',
  subjectMaxLength: 50,
  subjectMinLength: 5,
  bodyQuestion: '请输入详细描述(可选):',
  skipBody: true,
  skipBreakingChanges: true,
  issuesQuestion: '请输入要关闭的issue(可选,例如:#1):',
  skipIssues: false,
  openAiToken: null
}

export default config

Commit Type 详解

Type说明示例
feat新功能feat: add user authentication
fixBug 修复fix: resolve login timeout issue
docs文档变更docs: update API documentation
style代码格式style: format code with prettier
refactor代码重构refactor: simplify auth logic
perf性能优化perf: improve query performance
test测试相关test: add unit tests for auth
chore构建/工具chore: update dependencies
ciCI 配置ci: add GitHub Actions workflow
build构建系统build: upgrade webpack to v5
revert回滚提交revert: feat: add auth

Scope 最佳实践

推荐的 Scope 分类:

typescript
scopes: [
  '',              // 无特定范围
  'auth',          // 认证模块
  'api',           // API 层
  'components',    // 组件
  'utils',         // 工具函数
  'styles',        // 样式
  'config',        // 配置
  'deps',          // 依赖
  'docs',          // 文档
  'tests'          // 测试
]

3. 安装及配置 commitlint 校验工具

安装 commitlint 及 Husky 集成

shell
pnpm add --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/types husky
pnpm husky install

# 在package.json中配置脚本
npm pkg set scripts.commitlint="commitlint --edit"
echo "pnpm commitlint \${1}" > .husky/commit-msg
shell
npm install --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/types husky
npx husky install

# 在package.json中配置脚本
npm pkg set scripts.commitlint="commitlint --edit"
echo "npm run commitlint \${1}" > .husky/commit-msg
shell
yarn add --dev @commitlint/cli @commitlint/config-conventional @commitlint/types husky
yarn husky install

# 在package.json中配置脚本
npm pkg set scripts.commitlint="commitlint --edit"
echo "yarn commitlint \${1}" > .husky/commit-msg

Husky 是什么?

Husky 是一个 Git hooks 管理工具,让你可以轻松配置和管理 Git 钩子。

工作流程:

git commit

pre-commit hook (lint-staged)
    ↓ 格式化代码
commit-msg hook (commitlint)
    ↓ 校验提交信息
commit 成功

commitlint 配置示例

新建 commitlint.config.ts 文件

ts
import type { UserConfig } from '@commitlint/types'

const config: UserConfig = {
  extends: ['@commitlint/config-conventional']
}

export default config
js
export default { extends: ['@commitlint/config-conventional'] }

高级配置示例

typescript
// commitlint.config.ts
import type { UserConfig } from '@commitlint/types'

const config: UserConfig = {
  extends: ['@commitlint/config-conventional'],
  
  rules: {
    // type 必须存在
    'type-empty': [2, 'never'],
    
    // type 必须在枚举范围内
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'style',
        'refactor',
        'perf',
        'test',
        'chore',
        'ci',
        'build',
        'revert'
      ]
    ],
    
    // subject 不能为空
    'subject-empty': [2, 'never'],
    
    // subject 不以句号结尾
    'subject-full-stop': [2, 'never', '.'],
    
    // header 最大长度 100
    'header-max-length': [2, 'always', 100],
    
    // body 前需要空行
    'body-leading-blank': [2, 'always'],
    
    // footer 前需要空行
    'footer-leading-blank': [2, 'always']
  }
}

export default config

规则级别说明:

  • 0: 禁用规则
  • 1: 警告(warning)
  • 2: 错误(error,阻止提交)

CI 校验提交信息

GitHub Actions 示例,自动检查提交信息规范

.github/workflows/commitlint.yml
yml
name: CI

on: [push, pull_request]

jobs:
  commitlint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Install required dependencies
        run: |
          sudo apt update
          sudo apt install -y sudo
          sudo apt install -y git curl
          curl -sL https://deb.nodesource.com/setup_22.x | sudo -E bash -
          sudo DEBIAN_FRONTEND=noninteractive apt install -y nodejs
      - name: Print versions
        run: |
          git --version
          node --version
          npm --version
          npx commitlint --version
      - name: Install commitlint
        run: |
          npm install conventional-changelog-conventionalcommits
          npm install commitlint@latest

      - name: Validate current commit (last commit) with commitlint
        if: github.event_name == 'push'
        run: npx commitlint --last --verbose

      - name: Validate PR commits with commitlint
        if: github.event_name == 'pull_request'
        run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose

优化的 CI 配置

yaml
name: Lint Commits

on: [pull_request]

jobs:
  commitlint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Validate PR commits
        run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose

优势:

  • ✅ 使用官方 Node.js Action,更简洁
  • ✅ 使用 npm ci 确保依赖一致性
  • ✅ 仅在 PR 时检查,减少不必要的运行

完整工作流程示例

日常开发流程

bash
# 1. 修改代码
vim src/auth.ts

# 2. 添加到暂存区
git add src/auth.ts

# 3. 触发 pre-commit hook(自动格式化)
# lint-staged 会自动运行 prettier

# 4. 使用 commitizen 提交
npm run cz

# 交互式问答:
# ? 选择类型: feat
# ? 选择范围: auth
# ? 简短描述: add JWT token refresh
# ? 详细描述: (可选)
# ? 关联 issue: #123

# 5. 触发 commit-msg hook(校验格式)
# commitlint 检查是否符合规范

# 6. 提交成功

批量提交流程

bash
# 1. 修改多个文件
git add .

# 2. 自动格式化所有暂存文件
npx lint-staged

# 3. 查看将要提交的内容
git status

# 4. 使用交互式提交
npm run cz

# 5. 推送到远程
git push origin main

常见问题排查

Q1: Prettier 格式化后代码没变化?

可能原因:

  1. 文件在 .prettierignore
  2. 配置有误
  3. 文件类型不支持

解决方案:

bash
# 检查文件是否被忽略
prettier --check your-file.js

# 查看详细日志
prettier --write your-file.js --log-level debug

# 验证配置
prettier --find-config-path your-file.js

Q2: lint-staged 不生效?

检查清单:

bash
# 1. 确认 simple-git-hooks 已安装
npx simple-git-hooks

# 2. 检查 .git/hooks 目录
ls -la .git/hooks/pre-commit

# 3. 验证 package.json 配置
cat package.json | grep -A 5 "lint-staged"

# 4. 手动测试
echo "test" > test.txt
git add test.txt
git commit -m "test"

Q3: commitlint 校验失败?

常见错误:

⧗   input: fix bug
✖   subject may not be empty [subject-empty]
✖   type may not be empty [type-empty]

✖   found 2 problems, 0 warnings

解决方案:

bash
# 1. 使用正确的格式
git commit -m "fix: resolve login issue"

# 2. 或使用 commitizen
npm run cz

# 3. 查看规则详情
npx commitlint --help

# 4. 临时跳过(不推荐)
git commit -m "fix: bug" --no-verify

Q4: Husky hooks 丢失?

重新安装:

bash
# 删除旧 hooks
rm -rf .husky

# 重新安装
npx husky install

# 重新添加 hooks
npx simple-git-hooks

# 验证
ls -la .husky/

Q5: 团队协作配置不一致?

解决方案:

json
// package.json
{
  "engines": {
    "node": ">=18.0.0",
    "pnpm": ">=8.0.0"
  },
  "devDependencies": {
    "prettier": "3.1.0",  // 锁定精确版本
    "@commitlint/cli": "18.4.0"
  }
}

最佳实践:

  • ✅ 提交 .prettierrc.yaml 到版本控制
  • ✅ 提交 czvinyl.config.ts 到版本控制
  • ✅ 提交 commitlint.config.ts 到版本控制
  • ✅ 使用 --save-exact 锁定依赖版本
  • ✅ 在 README 中说明开发规范

最佳实践总结

1. 配置优先级

1. .prettierrc.yaml     # Prettier 配置
2. .prettierignore      # 忽略文件
3. czvinyl.config.ts    # Commitizen 配置
4. commitlint.config.ts # Commitlint 配置
5. package.json         # Scripts 和 lint-staged

2. 团队规范建议

代码风格:

  • ✅ 统一使用 Prettier 默认配置
  • ✅ 禁止手动修改格式化后的代码
  • ✅ IDE 配置保存时自动格式化

提交规范:

  • ✅ 每个 commit 只做一件事
  • ✅ 使用英文编写提交信息
  • ✅ 第一行不超过 72 字符
  • ✅ 详细说明"为什么"而非"做了什么"

工作流程:

  • ✅ 提交前自动格式化(lint-staged)
  • ✅ 提交时自动校验(commitlint)
  • ✅ CI 再次校验确保规范

3. IDE 集成

VS Code 配置:

json
// .vscode/settings.json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

推荐扩展:

  • Prettier - Code formatter
  • Commitizen Support
  • GitLens

总结

配置完整的代码格式化和 Commit 规范体系:

  1. Prettier:自动格式化,保持代码风格一致
  2. lint-staged:仅格式化暂存文件,提升性能
  3. Commitizen:交互式提交,降低规范门槛
  4. commitlint:自动校验,确保提交信息规范
  5. Husky:Git hooks 管理,自动化工作流

关键收益:

  • 🎯 代码质量提升 50%+
  • ⚡ Code Review 效率提升 30%+
  • 📊 提交历史清晰度提升 80%+
  • 🤝 团队协作成本降低 40%+

下一步学习:

开始规范化你的项目,提升团队协作效率!🚀✨