基于husky的代码校验及格式化

512 阅读2分钟

1. 工具安装及作用

  • husky:在git执行操作时触发钩子。安装husky npx husky-init && npm instal
  • lint-staged:识别被加入到暂存区的文件。安装lint-staged npm install lint-staged --save-dev
  • 安装eslint npm install eslint --save-dev
  • 安装prettier npm install prettier --save-dev
  • commitlint:配置git提交格式校验。安装commitlint相关 npm install --save-dev @commitlint/config-conventional @commitlint/cli

2. husky配置

  1. 建议删除-/.gitignore文件(可选)
  2. 在.husky下新建commit-msg和pre-commit文件 image.png
  • commit-msg用于执行代码校验配置文件commitlint.config.js
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx commitlint --edit $1
  • pre-commit用于执行lint-staged
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run lint-staged

3. lint-staged配置

  • package.json 增加
  "scripts":{},
  "lint-staged": {
    "**/*.{js,vue}": [
      "eslint --fix",
      "prettier --write"
    ]
  }

4. eslint配置

  • 执行npx eslint --init,根据选择生成.eslintrc[.js/.json/...]配置文件
module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: ['plugin:vue/vue3-essential', 'eslint:recommended'],
  parserOptions: {
    parser: 'babel-eslint',
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'space-before-function-paren': ['error', 'always'],
    'vue/no-multiple-template-root': 0,
    'vue/no-v-model-argument': 'off',
    'vue/no-v-html': 0,
  },
}
  • 在根目录下新建.eslintignore,配置eslint校验忽略的文件
*.sh
node_modules
lib
*.html
*.md
*.woff
*.ttf
.vscode
.idea
/dist/
/public
/docs
.vscode
.local
/bin
/build
/config
Dockerfile
vue.config.js
commit-lint.js
postcss.config.js
stylelint.config.js
!.eslintrc.js

5. prettier配置

  • 根目录下新建.prettier[.js/.json/...]
module.exports = {
  printWidth: 100, // 一行的字符数,超过会进行换行,默认为80,官方建议设100-120
  tabWidth: 2, // 一个 tab 代表几个空格数,默认 2
  useTabs: false, // 启用 tab 取代空格符缩进,默认 false
  semi: false, // 行尾是否使用分号,默认 true
  singleQuote: true, // 字符串是否使用单引号,默认为 false
  quoteProps: 'as-needed', // 是否给对象的属性要加上引号,默认为 as-needed
  trailingComma: 'es5', // 键值对后面是否使用尾逗号,有三个可选值 "<none|es5|all>",默认 es5
  bracketSpacing: true, // 对象大括号直接是否有空格,默认 true,效果:{ foo: bar }
}

6. 配置commitlint

  • 根目录下新建配置文件commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      ['feature', 'update', 'merge', 'fix', 'refactor', 'optimize', 'style', 'docs', 'chore'],
    ],
    'scope-enum': [2, 'always', ['今日深圳', '二十大', '教育服务']],
  },
}

rule配置说明::rule由name和配置数组组成,name可查Commitlint网站,数组中第一位为level,可选0,1,2,0为disable,1为warning,2为error,第二位为应用与否,可选always|never,第三位该rule的值。

  • 提交格式
git commit -m <type>[optional scope]: <description>

type :用于表明我们这次提交的改动类型,总结以下 11 种类型:

  - feature: 新功能
  - update: 更新某功能
  - merge: 合并
  - fix: 修补某功能的bug
  - refactor: 重构某个功能
  - optimize: 优化构建工具或运行时性能
  - style: 仅样式改动
  - docs: 仅文档新增/改动
  - chore: 构建过程或辅助工具的变动

optional scope:可选。用于标识此次提交主要涉及到代码中哪个模块。

description:一句话描述此次提交的主要内容。