Skip to content

开始

¥Get started

安装

¥Install

shell
npm install --save-dev husky
shell
pnpm add --save-dev husky
shell
yarn add --dev husky
# Add pinst ONLY if your package is not private
yarn add --dev pinst
shell
bun add --dev husky

¥husky init (recommended)

init 命令简化了在项目中设置 husky 的过程。它在 .husky/ 中创建一个 pre-commit 脚本,并在 package.json 中更新 prepare 脚本。可以稍后进行修改以适合你的工作流程。

¥The init command simplifies setting up husky in a project. It creates a pre-commit script in .husky/ and updates the prepare script in package.json. Modifications can be made later to suit your workflow.

shell
npx husky init
shell
pnpm exec husky init
shell
# Due to specific caveats and differences with other package managers,
# refer to the How To section.
shell
bunx husky init

试试看

¥Try it

恭喜!你已成功使用一个命令设置了第一个 Git 钩子 🎉。让我们测试一下:

¥Congratulations! You've successfully set up your first Git hook with just one command 🎉. Let's test it:

shell
git commit -m "Keep calm and commit"
# test script will run every time you commit

几句话...

¥A few words...

脚本

¥Scripting

虽然大多数情况下,你只需在钩子中运行一些 npm runnpx 命令,但你也可以使用 POSIX shell 编写脚本以实现自定义工作流程。

¥While most of the time, you'll just run a few npm run or npx commands in your hooks, you can also script them using POSIX shell for custom workflows.

例如,下面介绍如何在每次提交时仅使用两行 shell 代码且没有外部依赖来 lint 暂存文件:

¥For example, here's how you can lint your staged files on each commit with only two lines of shell code and no external dependency:

shell
# .husky/pre-commit
prettier $(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g') --write --ignore-unknown
git update-index --again

这是一个基本但有效的示例,如果你需要更多,请查看 lint-staged

¥This is a basic but working example, check lint-staged if you need more.

禁用钩子

¥Disabling hooks

Husky 不强制使用 Git 钩子。它可以全局禁用(HUSKY=0)或根据需要选择加入。有关手动设置和更多信息,请参阅 如何 部分。

¥Husky doesn't force Git hooks. It can be globally disabled (HUSKY=0) or be opt-in if wanted. See the How To section for manual setup and more information.