git commit时进行代码检查(lint-staged)配置

背景:团队开发为了保证提交代码格式统一,通常在进行代码提交的时候对暂存区代码进行校验,如没有通过eslint(本例使用eslint)校验,则不能提交到远端。

安装lint-staged

参考官网 https://github.com/okonet/lint-staged

npm install --save-dev lint-staged

设置lint-staged,在package.json或者新增一个配置文件(本例是在package.json,其他方式参考lint-staged官网)

"scripts": {
   "dev": "vite",
   "build": "vue-tsc && vite build",
   "preview": "vite preview",
   "lint": "eslint  './src/**/*.{js,jsx,vue,ts,tsx}' --fix",
 },
"lint-staged": {
   "*.{js,jsx,vue,ts,tsx}": [
     "npm run lint",
     "git add"
   ]
 },
  • npm run lint 是进行eslint 校验和--fix修改,通过后重新git add

设置pre-commitgit hook 来运行lint-staged

前置知识:
git hook是常说的 git 钩子,而pre-commit,该钩子在键入提交信息前运行。 它用于检查即将提交的快照(暂存区内容)。
钩子存储在项目的 .git/hooks。

参考官网 https://github.com/typicode/husky
install

npm install husky -D

package.json 增加配置

npm pkg set scripts.prepare="husky install"
npm run prepare

增加完成后package.json会增加一条prepare

"scripts": {
    "dev": "vite",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint  './src/**/*.{js,jsx,vue,ts,tsx}' --fix",
    "prepare": "husky install"
  },

添加 hook:

npx husky add .husky/pre-commit "npm test"
git add .husky/pre-commit

项目就会增加一个.husky文件夹


image.png

配置pre-commit

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm lint-staged

会报错
.husky/pre-commit: line 4: lint-staged: command not found

查阅解决方式:
添加npx lint-staged到预提交的 husky 文件中为我解决了这个问题

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged

效果:


image.png

本例使用包版本:

node : v16.18.1
husky: 8.0.3
lint-staged: 13.2.3
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容