You can use it to lint your commit messages, run tests, lint code, etc… when you commit or push. Husky supports all Git hooks
当您提交或推送时,您可以使用它来检查您的提交消息、运行测试、检查代码等。Husky 支持所有 Git 钩子
了解详情
husky-init 是快速初始化项目的一次性命令,非常方便
npx husky-init && npm install # npm
npx husky-init && yarn # Yarn 1
yarn dlx husky-init --yarn2 && yarn # Yarn 2
它将安装 husky
同时修改package.json
,并在项目根目录下创建.husky
文件夹
要添加其他的钩子,请使用 husky add
npx husky add .husky/pre-commit 'npm run test'
此时.husky
文件夹如下所示
.husky // 跟目录
├── _ // _ 文件夹
│ ├── .gitignore
│ └── husky.sh // shell 脚本
└── pre-commit // 自行添加的pre-commit 脚本,可配置eslint 和prettier 等脚本
npm install husky --save-dev
.husky
文件夹,目录结构同上自动安装的目录所示npx husky install
npm set-script prepare "husky install"
package.json 将自动添加以下脚本
{
"scripts": {
"prepare": "husky install"
}
}
npx husky add .husky/pre-commit "npm test"
yarn 安装请移步yarn安装
windowns :PowerShell标记“&&”不是此版本中的有效语句分隔符, 将“&&” 改成逗号
Windows 用户,编辑的脚本会报错,需要添加以下脚本
.husky/common.sh
command_exists () {
command -v "$1" >/dev/null 2>&1
}
# Workaround for Windows 10, Git Bash and Yarn
if command_exists winpty && test -t 1; then
exec < /dev/tty
fi
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
. "$(dirname -- "$0")/common.sh"
npm test
在提交代码之前运行检查更有意义。这样做可以确保没有错误进入存储库并强制执行代码样式。但是在整个项目上运行 lint 过程很慢,并且 lint 结果可能无关紧要。最终,您只想对将要提交的文件进行 lint。
该项目包含一个脚本,该脚本将使用暂存文件列表作为参数运行任意 shell 任务,并按指定的 glob 模式进行过滤。
开始使用 lint-staged 的最快方法是在终端中运行以下命令:
npx mrm@2 lint-staged
此命令将根据项目的 package.json
依赖项中的代码质量工具安装和配置 husky 和 lint-staged,在此之前请确保安装并配置所需代码质量工具,如 Prettier 和 ESLint 。
我项目中配置了eslint
, stylelint
, prettier
package.json 自动添加了以下配置
"lint-staged": {
"*.js": "eslint --cache --fix",
"*.css": "stylelint --fix"
}
同时自动配置了.husky
.husky
├── _
│ ├── .gitignore
│ └── husky.sh
└── pre-commit
lint-staged