All Resources
Tool
GitDevOpsAutomation
June 12, 2024

Git Hooks with Husky

Automate Git workflows with Husky - enforce code quality and prevent bad commits.

Overview

Husky makes Git hooks easy by providing a framework to manage pre-commit, pre-push, and other Git lifecycle hooks.

Common Hooks

  • pre-commit: Lint and format code before committing
  • commit-msg: Validate commit message format
  • pre-push: Run tests before pushing
  • post-merge: Install dependencies after pulling

Quick Start

npm install husky --save-dev
npx husky install

Add Pre-commit Hook

npx husky add .husky/pre-commit "npm run lint"
# .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run lint
npm run format
npm run type-check

Lint Staged Files

npm install --save-dev lint-staged
// package.json
{
  "lint-staged": {
    "*.{js,ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.json": ["prettier --write"]
  }
}
# .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged

Commit Message Validation

npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'style', 'refactor']],
    'subject-case': [2, 'never', ['start-case']]
  }
}

Pre-push Hook

# .husky/pre-push
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run build
npm run test

Husky prevents 90% of code quality issues from being committed to the repository.

Curated by

Shyam