使用Husky调用外部JS文件实现Commit Message验证失败
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 huskyoryarn list husky - For Husky v7+: You need to use the
.huskydirectory 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

