Skip to main content

husky-规范前端git操作

提示

本文使用huskV6版本

husky可以规范前端代码提交,可以再git提交的时候做一些事情,比如eslint检查,使用prettier对代码格式修复,强大的husky集成了githooks,可以更加方便的使用githooks。

类似的工具还有

快速上手

yarn add -D husky @commitlint/cli @commitlint/config-conventional

@commitlint/cli@commitlint/config-conventional对提交的msg进行检测。

在项目脚本里追加prepare

为什么需要husky install

// package.json
"script": {
"prepare": "husky install",
}

接下来配置commitlint

详细参数参考:https://commitlint.js.org/

// package.json 同层级 commitlint.config.js

module.exports = {
"extends": ["@commitlint/config-conventional"],
"rules": {
"type-enum": [
2,
"always",
[
"build",
"chore",
"ci",
"docs",
"feat",
"fix",
"perf",
"refactor",
"revert",
"style",
"test",
"record"
],
],
"type-empty": [0],
"type-case": [0],
"scope-empty": [0],
"header-max-length": [0, 'always', 72]
},
};

初始化husky

yarn prepare

项目目录结构

.husky/
├── _
│ └── husky.sh
└── .gitignore

创建一个sh文件,注意别加后缀.sh

.husky文件下建立一个无后缀文件commit -msg(这个就是git hooks

在其中追加如下代码,因为默认使用yarn环境,所以这里使用的是yarn

#!/bin/sh # 指定 shell 环境
. "$(dirname "$0")/_/husky.sh" # refer1

yarn commitlint --edit $1
$0,$1是什么

$0:就是该sh文件名

$1:是传递的第一个参数

所以上述refer1指的就是执行当前目录下./_/husky.sh脚本文件

然后执行yarn commitlint --edit[传递参数]

测试

git commit -m 'xxxx'

参数格式错误,会报如下错误

⧗   input: xxxx
✖ subject may not be empty [subject-empty]

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

然后将提交的内容修改正确便可以提交了

git commit -m 'feat: husky so cool~'