# husky

husky可以向项目中方便地添加git hooks。

# Lint-staged

Lint-staged:在暂存文件的时候能够避免错误格式代码提交到远程仓库。

提交代码前的检查是最后一个管控代码质量的一个环节,所以在提交代码之前进行lint检查意义重大。这样可以确保没有错误的语法和代码样式被提交到仓库上。 在整个项目上执行Lint进程会很低效,最好的做法就是检查那个被改动的文件。Lint-staged可以做到只检查暂存区改动的代码。

# git 提交代码开启强制校验

# 1、安装 npm 依赖

1、npm install --save-dev husky@7.0.0 lint-staged@11.2.6
2、npx husky-init && npm install
1
2

# 2、配置husky, 执行 githook 钩子开启代码提交校验

执行完成后,项目根目录会多出来 .husky 文件夹。

.husky文件夹下面的 pre-commit文件内容:

#!/bin/sh

. "$(dirname "$0")/_/husky.sh"

npx lint-staged

1
2
3
4
5
6

示例项目:package.json

{
  "name": "vue-simple-demo",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "prepare": "husky install"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^2.6.11",
    "vue-router": "^3.2.0",
    "vuex": "^3.4.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-prettier": "^6.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.8.0",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-vue": "^6.2.2",
    "husky": "^7.0.0",
    "lint-staged": "^11.2.6",
    "prettier": "^2.4.1",
    "sass": "^1.26.5",
    "sass-loader": "^8.0.2",
    "vue-template-compiler": "^2.6.11"
  },
  "lint-staged": {
    "*.{js,jsx,vue}": [
      "vue-cli-service lint"
    ]
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 3、 代码提交,验证

# 命令行提交命令
git add .
git commit -m 'first commit'
1
2
3

WARNING

lint-staged requires at least version 12.13.0 of Node, please upgrade

lint-staged 要求在12.13.0以上的node版本

更新时间: 12/10/2021, 4:47:49 PM