概覽:
prettier
eslint fix
git hook
commitlint
以配置js為例
第一步 格式化所有代碼 prettier
yarn add prettier -D
在package.json的script里面添加如下配置,注意修改成自己的文件路徑,采用glob配置。
"format":"prettier --single-quote --trailing-comma es5 --write \"src/**/*.js\"",
配置完畢,可以執行?yarn format測試一下。
更多配置訪問官網?https://prettier.io/docs/en/install.html
如果有eslint配置文件,會發現格式化之后,有些不符合eslint規范,配置eslint。
第二步 配置Eslint
yarn add -D eslint
假設你已經配置好eslint的配置文件 在package.json的scripts里添加如下,注意修改成自己的文件路徑。
"fix":"eslint --fix \"src/**/*.js\""
配置完畢。 執行完?yarn format之后再執行?yarn fix,完美自動格式化所有JS代碼。
此時我們配置format的語句如下:
"format":"prettier --single-quote --trailing-comma es5 --write \"src/**/*.js\" && yarn fix",
可以一次實現格式化和fix。
更多信息?https://eslint.org/
第三步 添加Git鉤子(Pre-commit Hook)
Git 鉤子(hooks)是在Git 倉庫中特定事件(certain points)觸發后被調用的腳本。 詳情可瀏覽?https://git-scm.com/book/zh/v2/%E8%87%AA%E5%AE%9A%E4%B9%89-Git-Git-%E9%92%A9%E5%AD%90
每次提交代碼,執行?git commit之后進行自動格式化,免去每次人為手動格式化,使遠程倉庫代碼保持風格統一。
yarn add lint-staged husky --dev
在package.json里面配置
{"scripts":{"precommit":"lint-staged"},"lint-staged":{"*.js":["yarn run format -- ","git add"]}}
配置完成。 這樣每次git commit 都會自動執行格式化并fix,成功之后會將格式化之后的文件自動add,然后統一commit。
第四步 添加git commit注釋規范
yarn add -D @commitlint/cli @commitlint/config-conventional
在根目錄下面添加commitlint.config.js文件,內容如下:
module.exports={extends:['@commitlint/config-conventional'],rules:{'type-enum':[2,'always',['merge','add','update','delete','feat','fix','docs','style','refactor','test','revert']],'subject-case':[0,'never',['lower-case']]}}
提交commit格式如下:
type: subjectName
bodyDetail
For example:
add: 添加了readme.md文件
添加了X的配置
添加了文檔
配置package.json
{"scripts":{"commitmsg":"commitlint -e $GIT_PARAMS"}}
配置完畢。
更多信息請查看:http://marionebl.github.io/commitlint/#/
現在提交代碼,只需要執行git commit然后格式化成功之后,進入默認編輯器(我的是VIM),填寫commit。wq保存就OK了。