Guides

Husky

Git hooks for commit validation and linting

Husky makes it easy to use Git hooks to enforce code quality and commit message standards.

Installation

npm add -D husky lint-staged
npm exec husky init

This creates a .husky/ directory and adds a prepare script to package.json.

Commit Message Validation

Create .husky/commit-msg to enforce commit message format:

commit-msg
commit_msg=$(cat "$1")

# Check if commit message starts with allowed prefixes
if ! echo "$commit_msg" | grep -qE "^(fix|feat|chores|other):"; then
  echo "Error: Commit message must start with one of: fix:, feat:, chores:, other:"
  echo "Example: feat: add new feature"
  echo ""
  echo "Your message: $commit_msg"
  exit 1
fi

Valid commit examples

git commit -m "fix: resolve login bug"
git commit -m "feat: add dark mode toggle"
git commit -m "chores: update dependencies"
git commit -m "other: misc cleanup"

Pre-commit Linting

Create .husky/pre-commit to run linting on staged files:

npm exec lint-staged

Configure lint-staged

Add to package.json:

package.json
{
  "scripts": {
    "lint": "eslint ."
  },
  "lint-staged": {
    "*.{js,ts,vue}": "eslint --fix"
  }
}

This only lints files being committed and auto-fixes issues where possible.

How it works

When you run git commit:

  1. pre-commit hook runs lint-staged on staged files
  2. ESLint checks and auto-fixes issues
  3. commit-msg hook validates the message format
  4. Commit succeeds or fails based on the checks

Manual linting

Run linting on the entire project:

npm run lint