工程中集成 husky、lint-staged、commitlint

最近在建立一个 webpack5+vue3+typescript+tsx 的一个vue工程,打算用来重构 vue-code-diffvue

原由

打算在代码提交时,进行 commit 信息格式以及提交内容的代码格式校验,防止出现代码风格和 commit 信息不统一问题,也为后期建立 change-logs 作准备。webpack

添加依赖

yarn add husky lint-staged @commitlint/cli @commitlint/config-angular -D
复制代码
  • husky: 提供githook,例如,咱们输入完 git commit -m 'xxxx' 后,就会触发 commit-msg钩子,就能够对 xxxx 内容进行咱们规定的格式校验了。
  • @commitlint/cli: 上面咱们提到对 xxxx 进行格式校验用的就是这个组件。
  • @commitlint/config-angular: 这个是 angular 的校验风格,我直接使用了这个。若是想自定义的话能够用 @commitlint/config-conventional 组件。
  • lint-staged: 主要做用是只校验咱们提交(git add .)的文件代码格式,而不是去校验全部的文件的格式,能够提升校验效率,否则项目大了以后,校验下数据格式估计就是5~6分钟了。

实战

先说一个坑,husky 在升级到6.0.0以后,改动极大。我最开始安装,配置完以后彻底没法触发 git 的 hook 。最后去查看官方文档,才发现如今网上的 husky 配置都是比较旧的,彻底不能使用。git

接下来咱们一步步操做。github

Enable Git hooks

这个 install 不是组件安装,而是至关于注册 husky-hook 到 git 上面。web

npx husky install
npm set-script prepare "husky install"
# 上面那行执行完以后会在 package 添加 "prepare": "husky install",目前不知道干啥用的。
复制代码

运行完上面的命令,工程下面会出现一个 .husky 文件夹,里面就是 hook shell,能够查看 .git/config 文件,发现多了下面的第8行。typescript

[core]
	bare = false
	repositoryformatversion = 0
	filemode = true
	ignorecase = true
	precomposeunicode = true
	logallrefupdates = true
	hooksPath = .husky
[remote "origin"]
	url = https://github.com/xxxxx.git
	fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
	remote = origin
	merge = refs/heads/master
[branch "v2.0.0"]
	remote = origin
	merge = refs/heads/v2.0.0
复制代码

建立 hook

npx husky add .husky/pre-commit "npm test"
复制代码

后面的 npm test 是钩子触发的时候,会运行的命令。 如今能够在工程下面的 .husky 文件架内多了一个 pre-commit 文件,内容为shell

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

npm test
复制代码

如今是否是对新版的 husky 使用有了相关的了解了。 接下来咱们把 lint-staged、commitlint 加上npm

commitlint

工程目录下建立 commitlint.config.jsjson

module.exports = {
  extends: [
    "@commitlint/config-angular"
  ]
};
复制代码

运行命令bash

npx husky add .husky/commit-msg "npm test"
复制代码

修改建立的 commit-msg 文件内容为

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

npx --no-install commitlint --edit $1
复制代码

关于以前的 HUSKY_GIT_PARAMS 已经用 $1 $2代替了。具体能够点击 HUSKY_GIT_PARAMS 查看

lint-staged

在工程目录下建立 .lintstagedrc.json 文件

{
  "src/**/*.{js,json,vue,ts,tsx}": [
    "eslint --fix"
  ]
}
复制代码

还记得咱们最开始实验室建立的 pre-commit 文件吗?直接修改他,删掉 npm test

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

npx --no-install lint-staged
复制代码

结束

看到这里,你的工程已经添加了对应的 git hook,若是还有问题,能够删除 .git/hooks/ 下面的 pre-commitcommit-msg 文件再试试。 新版的 husky 改动仍是很大的,把以前钩子从 .git/hooks 移出来,专门放在了一个文件夹内,因此致使了旧项目升级了 husky ,钩子就不起做用了。

相关文章
相关标签/搜索