使用Husky(哈士奇)管理Git项目

什么是 Husky(哈士奇)

Husky 就是狗,没错就是拆家的那家伙,也不知道@typicode是怎么想的,尽然起了这么有趣的一个项目名字

Husky 可以方便快速的使用Git hooks,帮你简单的配置项目,同时 Husky 可以将Git hooks同步到仓库,让整个团队能使用相同的Git hooks

什么是 Git Hooks

文档说明中文: https://git-scm.com/book/zh/v2/自定义-Git-Git-钩子
文档说明英文: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

因为提交到仓库后.git文件是不存在仓库中的,而Git hooks却在.git/hooks目录下

现在假设你是项目组长,一些项目需要使用的技术和库,需要你来配置,然后让小组成员去使用,那么当你使用了Git hooks后,只有你本地这台电脑能使用Git hooks,其它人Clone(克隆)Pull(拉取),都不会得到你配置的Git hooks,这时就可以使用Husky来同步Git hooks

安装 Husky

COPY
1
npm install husky -D

为什么使用prepare当作 key?
因为prepare是 npm 的生命周期命令,它会在npm install完成后执行,所以当如果有人克隆了项目并执行了npm install后就会自动初始化 husky 来管理 hook

编辑package.jsonscripts并并运行

COPY
1
2
npm set-script prepare "npx husky install"
npm run prepare

其中npm set-script命令仅限 npm 版本是 7.x 版本以上,如果不是则需要手动编辑

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "study-notes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"prepare": "husky install"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"husky": "^7.0.4"
}
}

添加 hook

举例:如果在进行 git commit 之前对代码进行eslint检查,那么可以使用pre-commit(这仅仅是个例子,你可以灵活的使用 hook 完成一些你想要完成的事情)

关于pre-commit的说明可以在官方文档查阅或是直接打开.git\hooks\pre-commit.sample查看注释说明

COPY
1
npx husky add .husky/pre-commit "npx eslint --fix"

当你执行git commit -m "xxx"提交代码之前就会自动执行 eslint

例如添加 hook 让他在提交代码前执行package.json中的 test 脚本

COPY
1
2
npx husky add .husky/pre-commit "npm test"
git commit -m "test husky pre-commit"

test 脚本输出一段内容 “Error: no test specified” 后还行了exit 1结束命令如下,由于执行了exit 1结束了命令(相当于我们按了ctrl+c一样)所以并未提交

COPY
1
2
3
4
5
6
7
$ git commit -m "test husky pre-commit"

> [email protected] test
> echo "Error: no test specified" && exit 1

"Error: no test specified"
husky - pre-commit hook exited with code 1 (error)
Authorship: Lete乐特
Article Link: https://blog.imlete.cn/article/Use-husky-manage-git-project.html
Copyright: All posts on this blog are licensed under the CC BY-NC-SA 4.0 license unless otherwise stated. Please cite Lete乐特 's Blog !