Automate Your Code Formatting with Prettier , Husky and Lint-Staged: A Complete Guide
Tags: prettier, husky, react, javascript
Published: 2023-03-24 19:02:16

As developers, we all want our code to be consistent and easy to read. After all, we don't want to read badly formatted code written by others.

![Gif description](https://media.giphy.com/media/VYAQdOdreGXTXu8jlT/giphy.gif)

However, when working in a team or on a large project, maintaining consistent code formatting can be a challenge. That's where Prettier and Husky come in.

Prettier is a popular code formatter that automatically formats code according to a set of rules. Husky is a popular Git hook manager that makes it easier to manage and configure Git. One can run scripts automatically before each commit, allowing developers to ensure that code is properly formatted before it is committed to the repository.

In this post, we'll walk through the steps of setting up Prettier and Husky to ensure consistent code formatting in your projects.

## Setting up Prettier


![Meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d67j407zmg0rh1eblp50.jpg)


The first step is to install the Prettier package in your project.

```bash
npm install --save-dev prettier
```

Next, you'll need to create a [configuration](https://prettier.io/docs/en/options.html) file for Prettier. This file should be named **.prettierrc** and should be located in the root directory of your project. Here's the one which I use mostly:

```json
{
	"parser": "babel",
	"arrowParens": "avoid",
	"trailingComma": "es5",
	"singleQuote": true,
	"semi": false,
	"useTabs": true,
	"tabWidth": 2,
	"jsxSingleQuote": true
}
```

This configuration file specifies that Prettier sets options such as using Babel to parse the code, omitting parentheses when possible for arrow function parameters, using a trailing comma if allowed by the language, using single quotes for string literals and JSX attributes, omitting semicolons, using tabs for indentation, and setting the tab width to 2 spaces.


## Setting Up Husky

Now that you've set up the Prettier configuration to format your code, it's time to set up Husky.

Step 1: Install Husky

First, you'll need to install Husky as a dev dependency in your project, as well as initialize it using `husky-init`.

```json
npx husky-init && npm install
```

It will set up husky, modify package.json and create a sample pre-commit hook that you can edit. By default, it will run npm test when you commit.

Step 2:

Configure Husky to run lint-staged before committing.
Open this file `.husky/pre-commit`. You can remove `npm test`, if it's not required.

```bash
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no-install lint-staged --allow-empty
```

* `--allow-empty`: By default, when linter tasks undo all staged changes, lint-staged will exit with an error and abort the commit. Use this flag to allow creating empty git commits.
    

Lint-staged will automatically run against staged files, and then add modifications to the commit as long as there are no errors. No need to do git add . anymore. 😌

Now, let's add this configuration to `package.json`

```json
"husky": {
	"hooks": {
		"pre-commit": "lint-staged"
	}
},
"lint-staged": {
	"*.{js,jsx}": [
		"npx prettier --config .prettierrc --write"
	]
},
```

The line `"*.{js,jsx}": ["npx prettier --config .prettierrc --write"]` uses a glob pattern to select all `.js` and `.jsx` files and then applies the Prettier formatting command to update those files.

## Testing

Now that you've set up Husky to run Prettier before each commit, you can test the setup by making changes to your code. Do git add . followed by git commit. Husky should automatically run lint-staged, which in turn will run Prettier before the commit is made, and you should see the changes reflected in the file.

References:

* [https://prettier.io/docs/en/configuration.html](https://prettier.io/docs/en/configuration.html)
    
* [https://typicode.github.io/husky/#/?id=automatic-recommended](https://typicode.github.io/husky/#/?id=automatic-recommended)
    
* [lint-staged](https://www.npmjs.com/package/lint-staged)