从零到一搭建一个基础项目模板(二) --- Git 提交规范

147 阅读1分钟

一. 安装 commitizen

pnpm add commitizen -D

二. 安装 cz-customizable

pnpm add cz-customizable -D

三. 在 package.json 中添加

"config": {
   "commitizen": {
     "path": "node_modules/cz-customizable"
   }
 }

四. 在根目录下新建 .cz-config.js 文件

module.exports = {
  types: [
    { value: 'feat', name: 'feat:  新功能' },
    { value: 'fix', name: 'fix:  修复' },
    { value: 'docs', name: 'docs:  文档变更' },
    { value: 'style', name: 'style:  代码格式(不影响代码运行的变动)' },
    { value: 'refactor', name: 'refactor:  重构(既不是作家feature,也不是修复bug)' },
    { value: 'perf', name: 'perf:  性能优化' },
    { value: 'test', name: 'test:  增加测试' },
    { value: 'chore', name: 'chore:  构建过程或辅助工具的变动' },
    { value: 'revert', name: 'revert:  回退' },
    { value: 'build', name: 'revert:  打包' },
  ],
  // 步骤
  messages: {
    type: '请选择提交的类型:',
    customScope: '请输入修改的范围(可选)',
    subject: '请简要描述提交(必填)',
    body: '请输入详细描述(可选)',
    footer: '请输入要关闭的issue (可选)',
    confirmCommit: '确认使用以上信息提交?( y/n ) ',
  },
  skipQuestions: ['body', 'footer'],
  subjectLimit: 72,
};

五. 使用 git Hook + husky 检查提交描述信息

pnpm add @commitlint/config-conventional @commitlint/cli husky -D

六. 初始化 husky

git init
npx husky install

在 package.json 中创建 script 命令

image.png 也可以通过命令行创建

npm set-script prepare "husky install"

运行初始化命令

pnpm prepare
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

测试一下

git add .
git commit -'test'

ERROR:
✖   subject may not be empty [subject-empty]

✖   type may not be empty [type-empty]

已处理好强制化提交功能,不符合的内容不能再被提交

七. 通过 pre-commit 检查提交的代码是否通过了 eslint 检验

通过 husky 添加 pre-commit hook 然后再通过指令进行 eslint 检测

npx husky add .husky/pre-commit "npx --no-install commitlint --edit $1"

安装 lint-staged 来自动修复 eslint 错误

pnpm add lint-staged -D

在 package.json 中添加 修复命令 和 启动命令

"lint-staged": {
  "*.{js,jsx,ts,tsx}": [
    "eslint --fix",
    "prettier --write"
  ],
  "{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": [
    "prettier --write--parser json"
  ],
  "package.json": [
    "prettier --write"
  ],
  "*.vue": [
    "eslint --fix",
    "prettier --write",
    "stylelint --fix"
  ],
  "*.{scss,less,styl,html}": [
    "stylelint --fix",
    "prettier --write"
  ],
  "*.md": [
    "prettier --write"
  ]
}
npm set-script lint:lint-staged "lint-staged"

打开 .husky 中的 pre-commit 文件 修改代码

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"

[ -n "$CI" ] && exit 0

# Format and submit code according to lintstagedrc.js configuration
npm run lint:lint-staged

在 .husky中添加 common.sh 文件

#!/bin/sh
command_exists () {
  command -v "$1" >/dev/null 2>&1
}
 
# Workaround for Windows 10, Git Bash and Yarn
if command_exists winpty && test -t 1; then
  exec < /dev/tty
fi

现在再测试一下, 代码可以自动修复了