You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Husky调用外部JS文件实现Commit Message验证失败

Troubleshooting Husky commit-msg Hook Not Executing Your Validation Script

Let’s walk through why your validation.js isn’t running as expected, and fix it step by step:

1. Check Your Husky Version (Critical!)

Husky changed its configuration approach drastically starting from version 7. If you’re using Husky v7+, your current package.json "commitmsg" setup won’t work—that was the old v4 syntax.

  • To check your version: run npm list husky or yarn list husky
  • For Husky v7+: You need to use the .husky directory setup instead of package.json scripts.

2. Fix Hook Configuration (For Husky v7+)

Here’s the correct way to set up the commit-msg hook:

  • First, enable Husky in your project:
    npx husky install
    
  • Add the commit-msg hook (this passes the commit message file path to your script):
    npx husky add .husky/commit-msg 'node ./validation.js "$1"'
    

3. Verify Your Script Path

Double-check that validation.js lives in your project root (adjust the path in the hook command if it’s in a subfolder, like node ./scripts/validation.js "$1").

Test if the script runs manually:

node validation.js

If you see Here... in the terminal, the script itself works—so the issue is likely the hook configuration.

4. Ensure Hook File Has Execute Permissions

On Unix-like systems, the .husky/commit-msg file needs execute permissions. If it doesn’t, run:

chmod +x .husky/commit-msg

5. Prepare Your Script for Real Validation

Right now your script just logs a message—here’s how to modify it to read and validate the commit message (once the hook is working):

const fs = require('fs');

// Get the path to the commit message file from the first argument
const commitMsgPath = process.argv[2];
const commitMsg = fs.readFileSync(commitMsgPath, 'utf8').trim();

console.log(`Validating commit message: ${commitMsg}`);

// Example rule: message must start with a valid type (feat, fix, etc.)
const validTypeRegex = /^(feat|fix|docs|style|refactor|test|chore): /;
if (!validTypeRegex.test(commitMsg)) {
  console.error('❌ Invalid commit message! Start with a type like "feat:", "fix:", etc.');
  process.exit(1); // Non-zero exit code rejects the commit
}

console.log('✅ Commit message is valid!');
process.exit(0);

For Husky v4 Users (If Sticking to the Old Version)

If you’re on Husky v4, adjust your package.json to use the correct hook syntax:

{
  "husky": {
    "hooks": {
      "commit-msg": "node validation.js"
    }
  }
}

Note: Husky v4 automatically passes the commit message file path as an argument, so you can still access it via process.argv[2] like in the script above.


内容的提问来源于stack exchange,提问作者Stilltorik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:02:58