Prettier 代碼格式化與 Commit 規範完全指南 | 提升團隊協作效率
在團隊協作開發中,代碼風格一致性和提交信息規範性是保證項目可維護性的關鍵。Prettier 是最流行的代碼格式化工具,而 Conventional Commits 規範則讓提交歷史清晰可讀。本文將詳細介紹如何為項目配置完整的代碼質量和提交規範體系。
為什麼需要代碼格式化和 Commit 規範?
核心痛點
| 問題 | 影響 | 解決方案 |
|---|---|---|
| 🎨 代碼風格不統一 | 閱讀困難,合併衝突多 | Prettier 自動格式化 |
| 📝 提交信息混亂 | 無法追溯變更原因 | Conventional Commits |
| 🔍 Code Review 低效 | 浪費時間檢查格式 | 自動化檢查 |
| 🚀 發佈日誌難生成 | 手動整理耗時 | 規範化自動生成 |
| 🤝 團隊協作成本高 | 新人上手慢 | 統一規範降低門檻 |
帶來的價值
✅ 提升代碼質量:統一的代碼風格,減少低級錯誤 ✅ 提高協作效率:清晰的提交歷史,便於追溯和回滾 ✅ 自動化工作流:CI/CD 自動校驗,減少人工干預 ✅ 專業形象:規範的開源項目更容易獲得信任 ✅ 長期可維護:標準化的代碼庫更易維護和擴展
1. 配置 Prettier 格式化代碼
安裝 Prettier 及相關插件
pnpm add --save-dev --save-exact prettier @trivago/prettier-plugin-sort-imports prettier-plugin-jsdoc prettier-plugin-packagejson prettier-plugin-sort-jsonnpm install --save-dev --save-exact prettier @trivago/prettier-plugin-sort-imports prettier-plugin-jsdoc prettier-plugin-packagejson prettier-plugin-sort-jsonyarn 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 文件鍵名 | 可選 |
安裝注意事項:
# --save-exact 鎖定精確版本,避免團隊環境不一致
# --save-dev 僅作為開發依賴
# 驗證安裝
npx prettier --versionPrettier 配置
新建 .prettierrc.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常用配置項詳解
# .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針對不同語言的配置:
# .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 配置如下
dist
pnpm-lock.yaml
cache
temp
.temp
*.vue常見忽略規則
# 依賴目錄
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 格式化所有文件
pnpm exec prettier . --writenpx prettier . --writeyarn prettier . --write常用命令選項
# 格式化並寫入
prettier --write .
# 僅檢查不修改(用於 CI)
prettier --check .
# 格式化特定文件類型
prettier --write "**/*.{js,ts,jsx,tsx,json,css,md}"
# 顯示幫助信息
prettier --help
# 查看配置解析結果
prettier --find-config-path .prettierrc.yaml批量格式化示例:
# 格式化 src 目錄下所有 TypeScript 文件
prettier --write "src/**/*.{ts,tsx}"
# 格式化所有 Markdown 文件
prettier --write "**/*.md"
# 排除特定目錄
prettier --write . --ignore-path .prettierignore配置 commit 自動格式化
安裝 simple-git-hooks 和 lint-staged 插件
pnpm install simple-git-hooks lint-staged工具說明:
- simple-git-hooks: 輕量級 Git hooks 管理工具
- lint-staged: 僅對暫存文件運行 linters,提升性能
配置 package.json 示例
{
"lint-staged": {
"*": ["prettier --write --ignore-unknown"]
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
}
}安裝 Git Hooks:
# 初始化 hooks
npx simple-git-hooks
# 驗證安裝
ls -la .husky/ # 或 .git/hooks/更精細的配置
{
"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 並配置
pnpm add --save-dev cz-vinyl commitizen
# 或者本地全局安裝
pnpm add -g cz-vinyl commitizennpm install --save-dev cz-vinyl commitizen
# 或者本地全局安裝
npm install -g cz-vinyl commitizenyarn add --dev cz-vinyl commitizen
# 或者本地全局安裝
yarn global add cz-vinyl commitizen查看本地全局安裝配置
- 在用戶主目錄創建
.czrc配置文件,指定適配器路徑
echo '{ "path": "cz-vinyl" }' > ~/.czrc- 給
cz命令設置別名,指向git-cz(cz-vinyl 的執行命令):
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 示例
{
"config": {
"commitizen": {
"path": "cz-vinyl"
}
},
"scripts": {
"cz": "git-cz"
}
}使用方法:
# 通過 npm script
npm run cz
# 或直接使用
npx git-cz
# 如果配置了別名
czcz-vinyl 選項配置示例
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 configCommit Type 詳解
| Type | 說明 | 示例 |
|---|---|---|
| feat | 新功能 | feat: add user authentication |
| fix | Bug 修復 | 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 |
| ci | CI 配置 | ci: add GitHub Actions workflow |
| build | 構建系統 | build: upgrade webpack to v5 |
| revert | 回滾提交 | revert: feat: add auth |
Scope 最佳實踐
推薦的 Scope 分類:
scopes: [
'', // 無特定範圍
'auth', // 認證模塊
'api', // API 層
'components', // 組件
'utils', // 工具函數
'styles', // 樣式
'config', // 配置
'deps', // 依賴
'docs', // 文檔
'tests' // 測試
]3. 安裝及配置 commitlint 校驗工具
安裝 commitlint 及 Husky 集成
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-msgnpm 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-msgyarn 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-msgHusky 是什麼?
Husky 是一個 Git hooks 管理工具,讓你可以輕鬆配置和管理 Git 鉤子。
工作流程:
git commit
↓
pre-commit hook (lint-staged)
↓ 格式化代碼
commit-msg hook (commitlint)
↓ 校驗提交信息
commit 成功commitlint 配置示例
新建 commitlint.config.ts 文件
import type { UserConfig } from '@commitlint/types'
const config: UserConfig = {
extends: ['@commitlint/config-conventional']
}
export default configexport default { extends: ['@commitlint/config-conventional'] }高級配置示例
// 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 示例,自動檢查提交信息規範
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 配置
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 時檢查,減少不必要的運行
完整工作流程示例
日常開發流程
# 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. 提交成功批量提交流程
# 1. 修改多個文件
git add .
# 2. 自動格式化所有暫存文件
npx lint-staged
# 3. 查看將要提交的內容
git status
# 4. 使用交互式提交
npm run cz
# 5. 推送到遠程
git push origin main常見問題排查
Q1: Prettier 格式化後代碼沒變化?
可能原因:
- 文件在
.prettierignore中 - 配置有誤
- 文件類型不支持
解決方案:
# 檢查文件是否被忽略
prettier --check your-file.js
# 查看詳細日誌
prettier --write your-file.js --log-level debug
# 驗證配置
prettier --find-config-path your-file.jsQ2: lint-staged 不生效?
檢查清單:
# 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解決方案:
# 1. 使用正確的格式
git commit -m "fix: resolve login issue"
# 2. 或使用 commitizen
npm run cz
# 3. 查看規則詳情
npx commitlint --help
# 4. 臨時跳過(不推薦)
git commit -m "fix: bug" --no-verifyQ4: Husky hooks 丟失?
重新安裝:
# 刪除舊 hooks
rm -rf .husky
# 重新安裝
npx husky install
# 重新添加 hooks
npx simple-git-hooks
# 驗證
ls -la .husky/Q5: 團隊協作配置不一致?
解決方案:
// 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-staged2. 團隊規範建議
代碼風格:
- ✅ 統一使用 Prettier 默認配置
- ✅ 禁止手動修改格式化後的代碼
- ✅ IDE 配置保存時自動格式化
提交規範:
- ✅ 每個 commit 只做一件事
- ✅ 使用英文編寫提交信息
- ✅ 第一行不超過 72 字符
- ✅ 詳細說明"為什麼"而非"做了什麼"
工作流程:
- ✅ 提交前自動格式化(lint-staged)
- ✅ 提交時自動校驗(commitlint)
- ✅ CI 再次校驗確保規範
3. IDE 集成
VS Code 配置:
// .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 規範體系:
- ✅ Prettier:自動格式化,保持代碼風格一致
- ✅ lint-staged:僅格式化暫存文件,提升性能
- ✅ Commitizen:交互式提交,降低規範門檻
- ✅ commitlint:自動校驗,確保提交信息規範
- ✅ Husky:Git hooks 管理,自動化工作流
關鍵收益:
- 🎯 代碼質量提升 50%+
- ⚡ Code Review 效率提升 30%+
- 📊 提交歷史清晰度提升 80%+
- 🤝 團隊協作成本降低 40%+
下一步學習:
開始規範化你的項目,提升團隊協作效率!🚀✨