git hooks进行代码检查

前置知识

git进行版本管理仓库时,在每个项目根目录下都有一个**.git/hooks**,包括commit各个阶段hooks的脚本,这些hooks在git操作commit、push、merge等的时候,可以做一些前置或后置的工作

工具

Husky && lint-staged

Husky作用:解决.git配置不能提交远程仓库的问题
lint-staged作用:对git暂存区代码文件进行bash命令操作,当前我们用来进行代码检查eslint

安装husky

npm install husky --save-dev
npm set-script prepare "husky install"
npm run prepare

安装lint-staged

npm install lint-staged  --save-dev

根目录下新建.lintstagedrc文件,如果要自动修复可以加上–fix

  "lint-staged": {
    "*.{css,scss,less}": [
      "git add"
    ],
    "*.{js,vue,jsx}": [
       "eslint",
       "git add"
    ]
  },

通过pre-commit检测提交时代码规范

npx husky add .husky/pre-commit "npx --no-install lint-staged"

修改pre-commit文件

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 使用本地资源,不下载
npx --no-install lint-staged

配置.eslintrc.js

module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
  },
  extends: [
    // 额外添加的规则可查看 https://vuejs.github.io/eslint-plugin-vue/rules/
    'plugin:vue/essential',
    'airbnb-base',
  ],
  parserOptions: {
    // 指定解析器 parser
    parser: 'babel-eslint',
    sourceType: 'module',
    ecmaVersion: 12,
    allowImportExportEverywhere: true, // 不限制eslint对import使用位置
  },
  settings: {
    'import/resolver': {
      webpack: {
        // 此处config对应webpack.config.js的路径,我这个路径是vue-cli3默认的路径
        config: 'node_modules/@vue/cli-service/webpack.config.js'
      }
    }
  },
  // 取消没必要的校验
  rules: {
    // 解决import/no-unresolved
    'import/extensions': [2, 'never', { js: 'never', json: 'never' }],
    'import/no-extraneous-dependencies': [2, { devDependencies: true }],
    'import/no-unresolved': [2, { ignore: ['antd-mobile'] }],
    // 关闭无关紧要的eslint
    'import/newline-after-import': 0,
    'import/no-cycle': 0,
    'vue/multi-word-component-names': 0,
    'vue/max-attributes-per-line': 0,
    'vue/attributes-order': 0,
    'vue/html-self-closing': 0,
    'max-len': 0,
    'comma-dangle': 0,
    'no-param-reassign': 0,
    'prefer-template': 0, // 使用es6拼接字符串
    'func-names': 0, // 无名函数
    'consistent-return': 0, // 有函数返回值
    'no-underscore-dangle': 0, // 不允许有下划线
    'no-use-before-define': 0, // 变量提升识别错误
    'no-unused-expressions': 0, // 使用函数代替表达式
    'no-restricted-syntax': 0, // 禁止使用特定的语法比如for in
    'no-plusplus': 0, // 不能用++
    'no-eval': 0, // 不能用eval
    'arrow-body-style': 0, // 箭头函数块周围禁止使用{}
    radix: 0, // 省略参数
    'linebreak-style': [0, 'error', 'window'], // 换行风格
  },
};

最后进行进行commit

git add .
git commit -m 'test: test git hooks'

你可能感兴趣的:(git,前端)