git hooks,即 git 钩子,定义为能在特定的重要动作发生时触发自定义脚本。
当您提交或推送时,您可以使用它来检查您的提交消息、运行测试、检查代码等。Husky 支持所有 Git 钩子。
1. 安装husky
npm install husky --save-dev
2. 启用 Git 挂钩
npx husky install
3. 要在安装后自动启用 Git 挂钩,请编辑package.json
// package.json
{
"scripts": {
"prepare": "husky install"
}
}
4. 创建一个钩子
要将命令添加到挂钩或创建新命令,请使用husky add <file> [cmd](不要忘记husky install之前运行)。
npx husky add .husky/pre-commit "npm test"
git add .husky/pre-commit
5.git commit 规范
安装 需要的依赖
npm i lint-staged
npm i react-dev-utils
在.husky下新建 commit-msg.sh
// commit-msg.sh
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no-install lint-staged
node scripts/verify-commit-msg.js `cat $1`
根目录新建 scripts/verify-commit-msg.js,规范提交信息
const chalk = require('react-dev-utils/chalk');
const msgPath = process.env.PWD + '/.git/COMMIT_EDITMSG';
const msg = require('fs').readFileSync(msgPath, 'utf-8').trim();
const commitRE =
/^(((\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]) )?(revert: )?(feat|fix|docs|UI|refactor|⚡perf|workflow|build|CI|typos|chore|tests|types|wip|release|dep|locale)(\(.+\))?: .{1,50}/;
if (!commitRE.test(msg)) {
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
`invalid commit message format.`,
)}\n\n${chalk.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`,
)}
${chalk.green(`💥 feat(compiler): add 'comments' option`)}
${chalk.green(`🐛 fix(compiler): fix some bug`)}
${chalk.green(`📝 docs(compiler): add some docs`)}
${chalk.green(`🌷 UI(compiler): better styles`)}
${chalk.green(`🏰 chore(compiler): Made some changes to the scaffolding`)}
${chalk.green(
`🌐 locale(compiler): Made a small contribution to internationalization`,
)}\n
${chalk.red(`See .github/commit-convention.md for more details.\n`)}`,
);
process.exit(1);
}
module.exports = () => {};
提交
git add .
git commit -m "feat: add husky"