前言

此前该部分内容记录在 create-react-app配置记录,随着husky6+后的更新,配置有很大的改变,特此新开一篇文章记录配置方法。

文档直通车:

安装依赖包

1
pnpm install husky lint-staged @commitlint/cli prettier -D

配置husky

  1. package.json 增加 prepare命令
1
2
npm set-script prepare "husky install" 
npm run prepare

运行完会在package.json中:

1
2
3
"scripts": {
+ "prepare": "husky install",
},
  1. 添加 pre-commit hook
1
2
3
# npm test 预提交 需要执行的命令,所以后面配置过程中此处还会被修改
npx husky add .husky/pre-commit "npm test"
git add .husky/pre-commit

以上命令运行完项目根目录下会生成一个.husky文件夹,并生成一个pre-commit文件,里面内容如下:

1
2
3
4
5
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm test

配置lint-staged

lint-staged帮助去做eslint和prettier;

.husky文件夹下新建.lintstagedrc.js文件,这个文件地址可以随意放置,也可以放在根目录下,内容如下:

1
2
3
4
module.exports = {
"*.{vue,js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{scss,less,html,md}": ["prettier --write"],
};

package.json中增加命令

1
"lint:lint-staged": "lint-staged --config ./.husky/.lintstagedrc.js"

.husky/pre-commit中将之前生成的npm test 命令修改成npm run lint:lint-staged

1
2
3
4
5
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run lint:lint-staged

配置commitlint

项目根目录下新增.commitlintrc.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module.exports = {
parserPreset: {
parserOpts: {
headerPattern: /^(\w*)(?:\((.*)\))?:\s(.*)$/,
headerCorrespondence: ["type", "scope", "subject"],
},
},
rules: {
"type-empty": [2, "never"],
"type-case": [2, "always", "lower-case"],
"subject-empty": [2, "never"],
"type-enum": [
2,
"always",
[
"feat",
"fix",
"docs",
"style",
"refactor",
"test",
"chore",
"release",
"revert",
],
],
},
};

添加 commit-msg hook:

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

命令执行之后.husky 文件夹下会生成一个叫commit-msg的文件:

1
2
3
4
5
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no -- commitlint --edit

配置完毕

配置成功,git提交控制台会显示:

1
2
3
4
5
6
7
8
9
10
11
12
13

xxxxx % git commit -m "feat: commit test"

> vue-project@0.0.0 lint:lint-staged
> lint-staged --config ./.husky/.lintstagedrc.js

✔ Preparing lint-staged...
✔ Running tasks for staged files...
✔ Applying modifications from tasks...
✔ Cleaning up temporary files...
[pc/vue3.2 460775a] feat: commit test
1 file changed, 1 deletion(-)