项目中采用 simple-git-hooks 代替 husky

1,495 阅读1分钟

安装 eslint simple-git-hooks

pnpm add eslint @antfu/eslint-config simple-git-hooks lint-staged -D

在src目录下创建 .eslintrc 文件

{
  "extends": "@antfu"
}

代码校验和格式化

在 package.json文件中加入

"scripts": {
    "lint": "eslint --ext .ts,.tsx,.vue,.js,.jsx src --fix",
    "postinstall": "simple-git-hooks"
  },
"simple-git-hooks": {
    "pre-commit": "pnpm lint-staged",
    "commit-msg": "node scripts/verifyCommit.js"
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx,vue}": "eslint --fix"
  },

同时创建 script文件夹 并添加 verifyCommit.js 文件

安装 chalk 包

pnpm add chalk -D

添加如下代码

// @ts-check
import { readFileSync } from 'node:fs'
import path from 'node:path'
import chalk from 'chalk'

const msgPath = path.resolve('.git/COMMIT_EDITMSG')
const msg = readFileSync(msgPath, 'utf-8').trim()

const commitRE
  = /^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
  console.log()
  console.error(
    `  ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
      'invalid commit message format.',
    )}\n\n${
      chalk.red(
        '  Proper commit message format is required for automated changelog generation. Examples:\n\n',
      )
      }    ${chalk.green('feat(compiler): add \'comments\' option')}\n`
      + `    ${chalk.green(
        'fix(v-model): handle events on blur (close #28)',
      )}\n\n${
      chalk.red('  See .github/commit-convention.md for more details.\n')}`,
  )
  process.exit(1)
}

最后执行

pnpm postinstall

以后的每次提交就有代码检测辣