Automate Code Formatting

September 10, 2023 Avishka Devinda

Have you ever found yourself in a situation where your codebase lacks consistency due to inconsistent code formatting? Fear not, as we have the perfect solution for you! In this blog post, we will guide you through setting up a pre-commit hook using Husky, Pretty-Quick, and Prettier to automatically format your code and keep it neat and tidy.

Step 1: Install Husky

To get started, open your terminal and run the following command to install Husky:

npm install husky

Next, add the following script to your package.json file:

// package.json
{
  "scripts": {
    "prepare": "husky install"
  }
}

Run npm prepare in your terminal to complete the Husky setup.

Step 2: Install Pretty-Quick and Prettier

Now, let's install Pretty-Quick and Prettier. Run the following commands:

pnpm add pretty-quick prettier

Step 3: Configure Husky Pre-Commit Hook

With Pretty-Quick and Prettier installed, it's time to set up the pre-commit hook. Run the following command:

npx husky add .husky/pre-commit "npx pretty-quick --staged"

This command configures Husky to run Pretty-Quick on every pre-commit, formatting only the staged files.

Make sure you have Prettier version ^2.8.8 installed, as higher versions may have compatibility issues with Pretty-Quick.

Step 4: Test Your Setup

With everything in place, it's time to test your setup. Make changes to your code and try committing using the following commands:

git add .
git commit -m "Add Pretty-Quick and Husky"

Husky will now automatically run Pretty-Quick before each commit, ensuring your code is formatted correctly.