Husky git Hook 工具

72 阅读1分钟

总是忘记git commit规范,每次提交都要面向百度,太浪费时间(影响摸鱼)记录已备后用

安装其他需要的依赖

npm i @commitlint/cli -D //自动化提示工具 约定提交规范
npm i cz-customizable -D // 自定义提示工具
// npm i commitlint-config-cz -D 如果要限制git提交日志规范,需要安装此依赖,
npm i commitlint-config-git-commit-emoji -D //提交类型图标

创建.cz-config.js文件

module.exports = {
    types: [
      {
        value: ':sparkles: feat',
        name: '✨ feat:     新功能'
      },
      {
        value: ':bug: fix',
        name: '🐛 fix:      修复bug'
      },
      {
        value: ':tada: init',
        name: '🎉 init:     初始化'
      },
      {
        value: ':pencil2: docs',
        name: '✏️  docs:     文档变更'
      },
      {
        value: ':lipstick: style',
        name: '💄 style:    代码的样式美化'
      },
      {
        value: ':recycle: refactor',
        name: '♻️  refactor: 重构'
      },
      {
        value: ':zap: perf',
        name: '⚡️ perf:     性能优化'
      },
      {
        value: ':white_check_mark: test',
        name: '✅ test:     测试'
      },
      {
        value: ':rewind: revert',
        name: '⏪️ revert:   回退'
      },
      {
        value: ':package: build',
        name: '📦️ build:    打包'
      },
      {
        value: ':rocket: chore',
        name: '🚀 chore:    构建/工程依赖/工具'
      },
      {
        value: ':construction_worker: ci',
        name: '👷 ci:       CI related changes'
      },
      { value: 'stage', name: 'stage: 暂存' },
      { value: 'merge', name: 'merge: 合并冲突' }
    ],
    messages: {
      type: '选择一种你的提交类型:',
      subject: '提交描述:\n',
      confirmCommit: '确定提交描述?'
    },
    skipQuestions: ['scope', 'customScope', 'body', 'breaking', 'footer'],
    subjectLimit: 100
}

创建commitlint.config.js文件

module.exports = {
    extends: ['git-commit-emoji', 'cz']
}

package.json添加

"scripts": {
    "commit": "git add . && cz-customizable",
}

安装husky

// npx husky-init && npm install 或以下方式
npm i husky -D
npx husky-init
//会自动创建一个.husky文件夹,
//在提交描述后执行.husky/pre-commit文件下的命令,可以修改为eslint等格式化操作...

//如果要限制git提交日志规范
//添加husky的commit-msg钩子,在提交前对提交信息进行检查(git提交时会先走pre-commit文件下的命令)
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
// 生成commit-msg文件失败的话分开执行(好像不能识别空格。。。)
npx husky add .husky/commit-msg
// 然后把里边的undefind 换成 'npx --no-install commitlint --edit "$1"'

使用

npm run commit

image.png

键盘上下选中后回车确认