JavaScript > Testing and Debugging > Debugging Tools > Code formatting with Prettier

Automated Formatting with Prettier using Husky

This snippet demonstrates how to set up a pre-commit hook using Husky and lint-staged to automatically format your JavaScript code with Prettier before each commit. This ensures that only formatted code is committed to the repository.

Installation

Install Husky, lint-staged, and Prettier as dev dependencies. Husky allows you to easily create Git hooks, lint-staged runs linters against staged git files, and Prettier formats your code.

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

Husky Setup

1. `npx husky install`: Initializes Husky in your project. 2. `npm set-script prepare "husky install"`: Adds a `prepare` script to your `package.json` file. This ensures that Husky is installed automatically when someone clones or installs your project. 3. `npm run prepare`: Executes the `prepare` script, installing Husky.

npx husky install
npm set-script prepare "husky install"
npm run prepare

Configure lint-staged

Add a `lint-staged` configuration to your `package.json` file. This configuration specifies which files lint-staged should run on and the commands to execute for each file type. In this example, all JavaScript, JSX, TypeScript, TSX, JSON and Markdown files are formatted with Prettier using the `--write` flag.

// package.json
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx,json,md}": ["prettier --write"]
  }
}

Create Pre-Commit Hook

This command creates a `pre-commit` hook in the `.husky` directory. The hook will run `npx lint-staged` before each commit. If lint-staged finds any unformatted code, it will format it and add the changes to the commit. If the formatting fails (e.g., due to a configuration error), the commit will be aborted.

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

Explanation of the Process

When you run `git commit`, the `pre-commit` hook is triggered. The hook executes `lint-staged`, which identifies the staged files matching the configured patterns (e.g., `*.js`). For each matching file, lint-staged runs the specified command (e.g., `prettier --write`). Prettier formats the files, and lint-staged adds the changes to the staging area. If everything is successful, the commit proceeds. Otherwise, the commit is aborted, and you need to fix the formatting issues before committing again.

Real-Life Use Case

In a team project, developers may forget to run Prettier manually before committing their changes. A pre-commit hook ensures that all code is automatically formatted before being committed, preventing unformatted code from entering the repository and maintaining a consistent code style across the project. This automated process significantly reduces the burden of code reviews and eliminates style-related discussions.

Best Practices

Ensure that all developers on the team have Husky and lint-staged installed correctly. Add a README section explaining the pre-commit hook setup and how it helps maintain code quality. Update the `lint-staged` configuration whenever you add new file types or change your formatting rules.

Interview Tip

Be able to explain how Git hooks work, the benefits of using pre-commit hooks, and how tools like Husky and lint-staged simplify the process of setting up and managing hooks. Demonstrate your understanding of how to automate code quality checks in a development workflow.

Alternatives

Alternatives include using `git hooks` directly without Husky. However, Husky makes managing Git hooks much easier and more portable. Another alternative is using a CI/CD pipeline to run code formatting checks after the code is pushed to the repository, but a pre-commit hook provides immediate feedback to the developer.

Pros

Automates code formatting, prevents unformatted code from being committed, improves code consistency, reduces code review time, provides immediate feedback to developers.

Cons

Requires initial setup and configuration, can slightly increase commit time, relies on developers having the correct tools installed.

FAQ

  • What if the pre-commit hook is causing issues and I need to bypass it temporarily?

    You can bypass the pre-commit hook by using the `--no-verify` flag with the `git commit` command: `git commit --no-verify -m "Your commit message"`. This will skip all Git hooks for that specific commit.
  • How do I update the Prettier version used by the pre-commit hook?

    Update the Prettier version in your `package.json` file using `npm install prettier@latest --save-dev` (or `yarn add prettier@latest --dev`). Then, ensure that the `lint-staged` configuration in `package.json` still uses the correct command to run Prettier with the updated version.
  • My pre-commit hook is not working. How can I troubleshoot it?

    1. Make sure Husky is installed and the `prepare` script has been run: `npm run prepare` 2. Check the `.husky/pre-commit` file to ensure it contains the correct command (`npx lint-staged`). 3. Verify the `lint-staged` configuration in `package.json` is correct. 4. Run `lint-staged` manually to see if it throws any errors: `npx lint-staged` 5. Check your Git configuration to ensure that hooks are enabled.