星际穿越

前端项目 git-commit 前自动格式化代码

2025-02-25

命令&配置

1
2
3
4
5
6
pnpm install -D simple-git-hooks
pnpm install -D lint-staged

# enable git hooks
npx simple-git-hooks
cat .git/hooks/pre-commit # check

package.json

1
2
3
4
5
6
7
8
9
10
{
"simple-git-hooks": {
"pre-commit": "npx lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"npx eslint --fix"
]
},
}

额外配置 prettier

.prettierrc

1
2
3
4
5
6
7
8
9
10
11
12
{
"arrowParens": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"printWidth": 80,
"proseWrap": "always",
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false
}

.prettierignore

1
pnpm-lock.yaml

package.json

1
2
3
4
5
6
7
8
9
10
{
"simple-git-hooks": {
"pre-commit": "npx pretty-quick --staged && npx lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"npx eslint --fix"
]
},
}

package.json 完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
"name": "my-react-movies",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"simple-git-hooks": {
"pre-commit": "npx pretty-quick --staged && npx lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"npx eslint --fix"
]
},
"dependencies": {
"@tailwindcss/vite": "^4.0.3",
"appwrite": "^17.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"tailwindcss": "^4.0.3"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.17.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.14.0",
"lint-staged": "^15.4.3",
"prettier": "3.4.2",
"pretty-quick": "4.0.0",
"simple-git-hooks": "^2.11.1",
"typescript": "~5.6.2",
"typescript-eslint": "^8.18.2",
"vite": "^6.0.5"
}
}