跳轉到內容

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%+

下一步學習:

開始規範化你的項目,提升團隊協作效率!🚀✨

最後更新於: