前端代碼風格自動化系列(二)之Commitlint

在有了Husky賦能以後,咱們有能力在Git的鉤子裏作一些事情,首先不得不提的是代碼的提交規範和規範的校驗,優雅的提交,方便團隊協做和快速定位問題。首推Commitlint,另外@加神 推薦了Gitmoji也是一個頗有意思的工具。git

安裝

npm install --save-dev @commitlint/config-conventional @commitlint/cli

// 生成配置文件commitlint.config.js,固然也能夠是 .commitlintrc.js
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js

配置

在husky的配置加入CommitlIint配置,v1.0.1版本之後爲HUSKY_GIT_PARAMSv0.14.3GIT_PARAMSgithub

"husky": {
    "hooks": {
      "pre-commit": "npm run test",
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"
    }
  },

定製提交規範

提交格式(注意冒號後面有空格)

<type>: <subject>

經常使用的type類別

  • upd:更新某功能(不是 feat, 不是 fix)
  • feat:新功能(feature)
  • fix:修補bug
  • docs:文檔(documentation)
  • style: 格式(不影響代碼運行的變更)
  • refactor:重構(即不是新增功能,也不是修改bug的代碼變更)
  • test:增長測試
  • chore:構建過程或輔助工具的變更

例子:npm

git commit -m 'feat: 增長 xxx 功能'
git commit -m 'bug: 修復 xxx 功能'

subject

subject是 commit 目的的簡短描述,能夠作一些配置,如最大長度限制。數組

commitlint.config.js文件配置

rule配置說明::rule由name和配置數組組成,如:'name:[0, 'always', 72]',數組中第一位爲level,可選0,1,2,0爲disable,1爲warning,2爲error,第二位爲應用與否,可選always|never,第三位該rule的值。具體配置例子以下:工具

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

這裏列出了大部分經常使用的配置,其它的能夠參考Commitlint網站,具體使用例子:測試

圖片描述

這裏咱們使用錯誤的提交方式,最上面的是自動測試的腳本,你們能夠忽略,husky給出了commit-msg的input爲xxx,觸發了subject-emptytype-empty兩個規則,提交不符合規範,被攔了下來。若是是正確的提交,例子以下:網站

圖片描述

關於Commitlint的使用就到這裏了。spa

相關文章
相關標籤/搜索