Husky and Git Hooks to make sure your code is clean, formatted and no-eslint error.
Whenever we writing any javascript, typescript app or working in a team of developers , We want to keep our code clean, formatted , buildable or any other action we want to happen before code is committed and pushed, husky and Git Hooks are there for help you.
With the help of Husky and Git hooks we can run certain command and scripts at time of committing, pushing source in repo.
What are Git hooks?
Git hooks are scripts that Git executes before or after events such as: commit, push, and receive. Git hooks are a built-in feature — no need to download anything. Git hooks are run locally.
There are various hooks provided by git . some of them are
- applypatch-msg
- pre-applypatch
- post-applypatch
- pre-commit
- prepare-commit-msg
- commit-msg
- post-commit
- pre-rebase
- post-checkout
- post-merge
- pre-receive
- update
- post-receive
- post-update
- pre-auto-gc
- post-rewrite
- pre-push
So we can use these triggers and use husky to perform some task in our project.
To Install husky in your project, you have to run below npm command
npm install husky --save-dev
Or
yarn add huskyit will add husky to devDependencies section of package.json and then we have to add husky section and specify what action we want to perform.
// package.json"scripts": {"lint": "run-p --print-label lint-eslint lint-markdown",
"lint-eslint": "eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./",
"lint-markdown": "markdownlint --ignore coverage --ignore dist --ignore examples --ignore node_modules **/*.md .**/**/*.md",
"test": "react-scripts test",
"test--coverage": "yarn run test -- --coverage",
"typecheck": "tsc --noEmit",
"validate": "run-p --print-label lint typecheck test build",
},
{
"husky": {
"hooks": {
"pre-commit": "lint",
"pre-push": "test",
"...": "..."
}
}
}Existing hooks are kept. Requires Node >= 10 and Git >= 2.13.0.
git commit -m 'Keep calm and commit'When git commit is executed ,lint script will execute and es-lint and lint-markdown will run on your source code.
When git push is executed , test will execute .
Starting with 1.0.0, husky can be configured using .huskyrc, .huskyrc.json or .huskyrc.js file.
// .huskyrc
{
"hooks": {
"pre-commit": "npm test"
}
}Supported hooks
Husky supports all Git hooks defined here. Server-side hooks (pre-receive, update and post-receive) aren't supported.
So using husky and git hooks , We can achieve prettier, error free , buildable code.