跳到主要内容

husky

在开发中,为了确保代码的质量和稳定性,我们需要将代码提交到仓库之前进行代码检查和测试。这个过程可以通过配置自动化脚本来实现,确保代码在提交前通过了代码验证工具的检验。

其实,Git 本身就设计了生命周期钩子来完成这个任务。但是设置过程比较复杂。所以通常情况下会使用 Husky 来简化配置。Husky 是一个 Git 客户端钩子工具,能够让你在 Git 生命周期事件之前或之后执行命令。它可以帮助我们配置 pre-commit、pre-push、commit-msg 等生命周期钩子来自动化检查代码质量和测试等工作,从而提高代码的质量和开发效率。 Husky

Git - githooks 首先,我们需要安装 Husky 工具,可以通过 shell 执行以下命令:

pnpm i husky -D

此命令会创建一个 npm script

pnpm set-script prepare "husky install"

githooks

在 commit 提交前执行 lint 代码校验

我们可以通过下面的命令来添加生命周期钩子:

npx husky add .husky/pre-commit "pnpm lint"

会创建 .husky/pre-commit 文件,其内容如下

.husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pnpm lint

在每次提交时,都将会执行 lint 脚本来检查代码。

在 push 之前通过单元测试

我们可以配置在 push 操作之前执行单元测试。不过更多的做法都是用 GitHub Action 配置 CI 在虚拟机上跑测试,而不是本地测试。如果确实需要在本地测试,可以执行以下命令:

npx husky add .husky/pre-push "pnpm test"

提交时自动检查 commit 信息是否符合要求

我们可以通过 commitlint 工具来检查 commit 信息是否符合规范。它会检查 commit message 中是否包含 type、scope、short title 和 body。如果不符合规范,就会在提交时提示用户。 commitlint - Lint commit messages

安装

pnpm i -g @commitlint/cli @commitlint/config-conventional

最后,将 commitlint 脚本添加到 githooks 中, 让每次提交前都验证信息是否正常。

echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

这样,每次用户在提交代码之前,都会进行规范校验,如果不符合提交规范,就会提示用户按照正确的格式重新提交。 :::caution 注意

windows 系统请勿使用上行命令,否则会导致编码不是 UTF-8。建议直接复制文本内容到 commitlint.config.js

commitlint.config.js
module.exports = { extends: ['@commitlint/config-conventional'] }

:::

将 commitlint 脚本添加到 githooks 中, 让每次提交前都验证信息是否正常。

npx husky add .husky/commit-msg "npx --no-install commitlint --edit "$1""

其内容如下

.husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit "$1"

测试 commit 提交 echo 'foo: bar' | commitlint 将会报错,不符合 commit msg 规范。

echo 'foo: bar' | commitlint
⧗ input: foo: bar✖ type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test] [type-enum]

✖ found 1 problems, 0 warnings
Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint

其他选择

除了 Husky 之外,还有一些其他的工具也可以用于检查代码质量和测试。例如,Simple Git Hooks,它提供了一种简单的方式来执行 Git 钩子并验证代码规范和测试用例。通过配置它,我们可以在使用原生 Git 钩子时不需要写复杂的脚本来执行 Git 的操作。 simple-git-hooks