A quick way to add Git pre-commits hooks into an Angular Project
1 min read
Setup with Husky
This is the pre-commit hook setup strategy I followed in our Angular projects. By setting this hook we can ensure that committed code will be linting error-free and formatted with Prettier code-formatter.
Step 1
We install the following devDependencies
yarn add husky lint-staged prettier -D
huskymakes it easy to use githooks as if they are npm scripts.lint-stagedallows us to run scripts on staged files in git.prettieris the JavaScript formatter we will run before commits.
Step 2
Once those are installed, we add the below configuration to package.json file:
"devDependencies": {
// ...
},
"lint-staged": {
"src/**/*.{js,ts,scss,md,html,json}": [
"prettier --write"
]
},
"husky": {
"hooks": {
"pre-commit": "ng lint && lint-staged",
"pre-push": "ng build --configuration production"
}
}
Usage
Next time when you commit the changes, this script will auto-execute and will
run ng lint first to lint the files. If there are any errors in formatting or
coding style, then it will not proceed to commit the files, otherwise, the
staged files will be formatted automatically and will be committed. 🥳