Step-by-Step Guide: Using Prettier and Husky for Automatic Code Formatting

Step-by-Step Guide: Using Prettier and Husky for Automatic Code Formatting

Step 1: What is Prettier and Husky

Prettier is a code formatter that ensures a consistent style by parsing your code and reprinting it according to its own rules. Husky is a tool that helps you manage Git hooks easily, allowing you to automate tasks like code formatting before commits.

Step 2: Install Prettier, Husky, and lint-staged

First, install Prettier, Husky, and lint-staged as development dependencies in your project:

npm install --save-dev prettier husky lint-staged

Step 3: Configure Prettier

Create a .prettierrc file in the root of your project to configure Prettier according to your preferences. For example:

{
    "singleQuote": false,
    "bracketSpacing": true,
    "tabWidth": 4,
    "semi": true
}

Step 4: Create a .prettierignore File

To prevent Prettier from formatting certain files or directories, create a .prettierignore file in the root of your project. This file works similarly to a .gitignore file. Add the paths you want to exclude from formatting. For example:

node_modules
build
dist

This step ensures that Prettier ignores the specified files and directories during the formatting process.

Step 5: Add a Pre-commit Hook

Create a pre-commit hook that runs lint-staged to format only the staged files:

npx husky add .husky/pre-commit "npx lint-staged"

This command will create a .husky/pre-commit file with the following content:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged

Step 6: Configure lint-staged

Configure lint-staged to run Prettier on your staged files. Add the following configuration to your package.json:

{
    "husky": {
        "hooks": {
            "pre-commit": "lint-staged"
        }
    },
    "lint-staged": {
        "src/**/*.{js,jsx,ts,tsx}": [
            "prettier --write",
            "git add"
        ]
    }
}

This configuration tells lint-staged to format any staged file matching the specified extensions using Prettier.

Step 7: Commit Your Changes

After setting up everything, you can commit your changes. When you run git commit, Husky will trigger the pre-commit hook, and lint-staged will format the staged files using Prettier. Here's an example of what the output might look like:

git add .
git commit -m "Add new feature"

# Example output:
# > husky - pre-commit hook
# > lint-staged
# ✔ Preparing...
# ✔ Running tasks...
# ✔ Applying modifications...
# ✔ Cleaning up...
# [main 1a2b3c4] Add new feature
#  2 files changed, 10 insertions(+), 2 deletions(-)

Conclusion

By following these steps, you’ve set up an automated system that ensures your code is always formatted according to your Prettier configuration before every commit. This integration not only enforces consistency across your project but also reduces the manual effort required during code reviews.