husky7.0.1 + commitlint 配置提交代碼檢查和規範踩坑指南

Lynne,一個能哭愛笑永遠少女心的前端開發工程師。身處互聯網浪潮之中,熱愛生活與技術。(實際上是一隻沒有對象莫得感情的機器加班狗。)前端

背景

最近新起了一個後臺項目,還要遷移舊的項目代碼,練手之餘各類踩坑,臨近上線纔想起來添加commit提交代碼前格式化檢查代碼並規範提交信息。vue

在團隊多人開發中,規範的commit message能夠快速定位代碼提交歷史,回溯問題根源,方便組內多人協做,提升團隊效率。git

因爲個人項目採用的是 husky + commitlint 配置,接下來圍繞這兩個簡要介紹下個人踩坑史。github

注: husky 6.0.0 版本發生了破壞性變動,下述方案使用的是 7.0.1 版本husky,對於低於 6.0.0 版本不適用,低於7.0.1 版本husky也可能存在問題。web

husky 安裝

參考 husky 的README:GitHub husky 小白若是看着有疑問能夠跟着個人步驟來:shell

一、項目內安裝

npm i lint-staged husky -save-dev
複製代碼

二、建立.husky/目錄並指定該目錄爲git hooks所在的目錄

在package.json中添加prepare腳本npm

{
  "scripts": {
      "prepare": "husky install"
  }
}
複製代碼

prepare腳本會在執行npm install以後自動執行。也就是說當咱們執行npm install安裝完項目依賴後會執行 husky install命令。json

或者採用命令行方式:markdown

注: 須要npm版本Version 7.x(npm set-script命令須要7.x)ide

npm set-script prepare "husky install" && npm run prepare
複製代碼

三、添加git hooks

建立一條 pre-commit hook

npx husky add .husky/pre-commit "npm run lint"
複製代碼

執行該命令後,會看到.husky/目錄下新增了一個名爲pre-commit的shell腳本。

這樣,在以後執行git commit命令時會先觸發pre-commit這個腳本。

pre-commit腳本內容以下:

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

npm run lint
複製代碼

注意:npm run lint 命令根據你本身項目中script腳本而定,eslint --ext .js,.vue src在lint腳本中

四、規範commit message信息

相似的,咱們也能夠添加commit-msg鉤子,來規範咱們的commit message信息

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"' 
複製代碼

husky 使用

隨便commit一下

git commit -m "feat: pre-commit優化"
複製代碼

建立了 pre-commit hook以後,在每次執行 git commit 或者 git commit --amend時,都會先觸發pre-commit hook,來執行npm run lint中包含的 eslint 等代碼檢測工做。

理論上,這樣就能夠有效避免將存在 eslint error 的代碼提交到遠程倉庫了~~~

可是點擊執行後卻報錯了:

> eslint --ext .js,.vue src

not found: commitlint
husky - commit-msg hook exited with code 127 (error)
複製代碼

commitlint 安裝與配置

錯誤提示咱們須要安裝安裝 commitlint。

npm i @commitlint/cli @commitlint/config-conventional -D
複製代碼

接下來繼續commit結果又報錯了....害!

> eslint --ext .js,.vue src

⧗   input: feat: pre-commit優化
✖   Please add rules to your `commitlint.config.js`
    - Getting started guide: https://git.io/fhHij
    - Example config: https://git.io/fhHip [empty-rules]

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

husky - commit-msg hook exited with code 1 (error)
複製代碼

提示可知要配置 commitlint.config.js

因而

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

ok!~~~大功告成!

相關文章
相關標籤/搜索