~1 min read

A quick way to add Git pre-commits hooks into an Angular Project

If you work in an environment where a pipeline is used for Continuous Integration, pre-commit hooks are incredibly important. Pre-committing allows us to both ensure we write quality code as well as save ourselves from embarrassment by catching bugs before anyone else does. Let's see how we can do this in an Angular project

ok Setup with Husky

This is the pre-commit hook set up a strategy I followed in our angular projects. By setting this hook we can ensure that committed codes 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

  • husky makes it easy to use githooks as if they are npm scripts.
  • lint-staged allows us to run scripts on staged files in git.
  • prettier is the JavaScript formatter we will run before commits.

 

Step 2

Once those are installed, we add the below configuration to package.json file:

 

1 "devDependencies": { 2 // ... 3 }, 4 "lint-staged": { 5 "src/**/*.{js,ts,scss,md,html,json}": [ 6 "prettier --write", 7 "git add" 8 ] 9 }, 10 "husky": { 11 "hooks": { 12 "pre-commit": "ng lint && lint-staged", 13 "pre-push": "ng build --prod" 14 } 15 }

 

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. 🥳