husky: 添加 prettier 的正确“姿势”
在项目中添加 prettier 的正确方法
安装
# 安装 husky
yarn add husky --dev
npm pkg set scripts.prepare="husky install"
npm run prepare
yarn add --dev prettier lint-staged
husky v9
添加 lint-staged
配置
- 注意 prettier: 只专注格式化,不管 staged
- eslint 也只管 lint
{
"name": "alo7-web-react",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"pretty": "prettier --write src",
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 10",
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"npm run pretty",
"npm run lint"
]
}
}
husky 添加 pre-commit
提前之前执行此脚本
# 这个 husky add 好像已经失效了
npx husky add .husky/pre-commit "npx lint-staged"
确认上面命令产生的文件内容如下
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
其它
格式化,只有变化的,不依赖
lint-staged
参考: https://www.banjocode.com/post/git/prettier-on-changed-files
npx prettier --write $(git diff --name-only --diff-filter d | grep '.ts$' | xargs)
老版本
公司里可能老项目,配置方法略有不同。
{
"name": "myapp",
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["npm run prettier:fix", "npm run lint:check"]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
跳过检测
在实际中,会出一些莫名的问题,需要“
暂时性
”跳过。参考: https://stackoverflow.com/questions/63943401/husky-pre-commit-hook-failed-add-no-verify-to-bypass
git commit -m "chore: rm unused pkgs" --no-verify
参考
- https://github.com/lint-staged/lint-staged
- https://stackoverflow.com/questions/47610213/how-do-i-run-prettier-only-on-files-that-i-want-to-commit
- https://blog.stackademic.com/adding-eslint-and-prettier-to-a-vitejs-react-project-84a0752c0fc5
- https://lightrun.com/answers/okonet-lint-staged-prettier---write-command-changed-not-only-staged-files-
- https://dev.to/darraghor/how-to-list-files-changed-in-current-branch-and-run-prettier-on-them-38oe
- https://rushjs.io/pages/maintainer/enabling_prettier/