Husky and Commitlint are a compact, reliable combo for keeping Git histories tidy. Husky wires Git hooks into your npm scripts, and Commitlint enforces commit-message conventions.
This short guide shows a pragmatic setup: use Husky to run lint-staged in a pre-commit hook for code quality, and run Commitlint in a commit-msg hook to validate commit messages.
Install the tools
npm install --save-dev husky lint-staged @commitlint/config-conventional @commitlint/cliHusky setup
{
"scripts": {
"prepare": "husky install"
}
}npx husky install
npx husky add .husky/pre-commit "npx --no -- lint-staged"
npx husky add .husky/commit-msg "npx --no -- commitlint --edit $1"Commitlint config
module.exports = {
extends: ['@commitlint/config-conventional'],
};Lint-staged example
{
"lint-staged": {
"src/**/*.{js,ts,jsx,tsx}": [
"eslint --fix",
"prettier --write",
"git add"
],
"src/**/*.{css,md}": [
"prettier --write",
"git add"
]
}
}Example commit message
A passing Conventional Commit looks like:
feat(auth): add OAuth2 redirect support
Adds a new redirect handler and tests for OAuth2 flows.The commit-msg hook will reject messages that do not follow the configured rules.
Troubleshooting
If hooks don't run after clone, run npm run prepare or npx husky install. CI should also run commitlint and linters to be safe.