为项目添加 ghooks + validate-commit-msg
以下是为项目添加 ghooks 和 validate-commit-msg 来实现 git 提交检查的步骤:
1. 安装必要的依赖包
首先,需要安装 ghooks 和 validate-commit-msg 作为开发依赖:
bash
npm install ghooks validate-commit-msg --save-dev
2. 配置 package.json
在 package.json 文件中添加 ghooks 的配置,指定需要运行的 git 钩子:
json
"config": {
"ghooks": {
"pre-commit": "npm run lint",
"commit-msg": "validate-commit-msg"
}
}
同时,确保项目中有 lint 脚本:
json
"scripts": {
"lint": "eslint ."
}
3. 确保 ESLint 配置正确
根据你使用的 ESLint 版本,选择正确的配置方式:
-
对于 ESLint v9.0.0 及以上版本,需要创建
eslint.config.js
文件(CommonJS 格式):javascriptconst globals = require('globals'); const js = require('@eslint/js'); module.exports = [ { files: ['**/*.js'], languageOptions: { ecmaVersion: 12, sourceType: 'module', globals: { ...globals.node, ...globals.es2021 } }, rules: { ...js.configs.recommended.rules, 'no-console': 'warn', 'semi': ['error', 'always'], 'quotes': ['error', 'single'] } }, { ignores: ['node_modules/', 'dist/'] } ];
-
对于 ESLint v8.x 及以下版本,可以使用传统的
.eslintrc.json
文件。
4. 确保 git 钩子路径配置正确
这是非常重要的一步,确保 git 没有配置错误的钩子路径:
bash
# 检查当前 git hooks 路径配置
git config core.hooksPath
# 如果有错误的配置,重置为默认值
git config --unset core.hooksPath
5. 重新安装依赖以触发 ghooks 初始化
bash
npm install
执行此命令后,ghooks 会自动在 .git/hooks
目录下创建相应的钩子文件。
6. 验证安装是否成功
可以通过以下方式验证安装是否成功:
-
检查 .git/hooks 目录:确认 pre-commit 和 commit-msg 文件是否存在且有执行权限
-
测试 ESLint 命令:
bashnpm run lint
-
测试提交消息验证:
bash# 测试有效格式 npx validate-commit-msg 'feat: add new feature' # 测试无效格式 npx validate-commit-msg 'xxxxx'
-
实际测试 git 提交:尝试进行一次 git 提交,检查是否会执行 ESLint 和提交消息验证
常见问题及解决方案
-
钩子不执行:检查 git hooks 路径配置是否正确
-
ESLint 报错:确保使用了与 ESLint 版本匹配的配置文件格式
-
Windows 环境问题:确保钩子文件有正确的执行权限
-
钩子路径冲突:避免同时使用多个 git hooks 管理工具(如 husky 和 ghooks)
通过以上步骤,你可以成功为项目添加 ghooks 和 validate-commit-msg,实现 git 提交时的代码质量和提交消息格式检查。