Pre-commit and Pre-push Hook Setup with Husky
Automate code quality checks with Git hooks using husky and lint-staged to run linters, formatters, and tests before commits and pushes.
Prerequisites
- -Node.js and npm installed
- -A Git repository with a package.json
- -ESLint, Prettier, or another linter configured
Steps
Install husky and lint-staged
Install husky for managing Git hooks and lint-staged for running linters on only staged files, keeping hooks fast.
Initialize husky
Sets up the .husky directory and adds a prepare script to package.json so hooks are installed automatically when anyone runs npm install.
Configure lint-staged in package.json
Define which commands to run on staged files by file extension. This runs ESLint and Prettier on JS/TS files, and Prettier alone on JSON/MD/CSS.
Lint-staged only processes files that are staged for commit, making hooks fast even in large repositories.
Create the pre-commit hook
Create a pre-commit hook that runs lint-staged. This will lint and format only the files being committed.
Create a pre-push hook for tests
Add a pre-push hook that runs the test suite before allowing a push. The --bail flag stops at the first failure for fast feedback.
Pre-push hooks that run a full test suite can be slow. Consider running only critical tests or tests related to changed files.
Test the hooks with a commit
Make a small change and commit to verify the pre-commit hook triggers lint-staged, which runs ESLint and Prettier on the staged file.
If a hook fails, the commit is aborted. Fix the issues reported by the linter and try committing again.
Full Script
FAQ
Discussion
Loading comments...