Set up ESLint, Prettier and Husky in a React project | a step by step guide
Tags: eslint, prettier, husky, react
Published: 2022-05-01 17:02:44

When setting up a new project, especially the one that will be worked on by many people (team), code quality is an important aspect to put into consideration to make your codebase cleaner and standardized. That's why we need to use different tools that ensure our code quality. in this tutorial I will walk you step by step into setting up Eslint, Prettier and Husky and getting them ready to work in your next project 

For this example, we will be setting up these tools in React Project and we will be using Eslint with Airbnb configurations

**Prerequisites**
- This is a second blog in the series of setting up a React environment from scratch therefore I assume that you already have a React project built in the first blog. if not refer to first blog [HERE](https://dev.to/yvad60/how-to-create-a-react-app-without-using-create-react-app-a-step-by-step-guide-30nl). You can also follow along if you want to use this article for other purposes.
- **Node**: we will be working in the node environment therefore you will need to have it installed on your machine 
- **VSCode**: as our code editor 

that's all you need let's get started...

**Understanding these tools**
the main point of these tools is to ensure the quality of your code when working alone or working as a team

- **Eslint:** is a linter for JavaScript, linters are tools that will help you set up rules to follow as you write your code and they ensure that you follow your rules.
- **Prettier:** Is a code formatter that automatically formats your code to look cleaner and easier to read there are several code formatter but prettier is the most popular one
- **Husky:** is a tool that allows us to run scripts especially while using version control like `git` for our example we will be using husky to set up pre-commit scripts to run prettier and Eslint on every commit. You need to be working in a git repository to be able to use Husky
we will get back to these tools later in the guide for now 

follow the following steps

**1. Create a node project**
As mentioned I will be starting with code from the first article about [creating react app from scratch without create-react-app](https://dev.to/yvad60/how-to-create-a-react-app-without-using-create-react-app-a-step-by-step-guide-30nl). currently my folder structure looks like this

![starting folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cn8p3lwakbq5ycddh40d.png)
if you are not following the first article you can just create a new folder, open it in VSCode and run `npm init -y` this will initialize a new node project and add the `package.json` file.
```
npm init -y
```
**2. Installing Eslint dependencies**
Eslint is a lint for identifying and reporting on patterns found in ECMAScript/JavaScript code. lints or linters are tools that are used to flag programming errors, bugs, stylistic errors, and suspicious constructs to reduce errors and improve the overall quality of your code in some cases they can spot those errors and auto-fix them for you. 
Eslint specifically is a popular open-source lint that works best with JavaScript and TypeScript, it allows us to configure and customize it to our needs by specifying your own rules or extending standardized rules from companies like Google, Airbnb...

Run the following command to install ESLint (as a dev dependency)

```
npm install eslint --save-dev
```

**3. Configuring ESLint**
in this guide, we will be configuring ESLint with Airbnb JavaScript styles which are standard when it comes to JavaScript. This means that Eslint will check our code according to what's allowed and not allowed by the Airbnb style guide you can learn more about the Airbnb JavaScript style guide [here](https://github.com/airbnb/javascript)

follow this step to configure Eslint
```
npm init @eslint/config
```
you will need to answer some questions about how you would like to use eslint follow the following configuration

![ESLint configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6i3hg748wk0qcfrby3s.gif)
(note that I chose react as the library, Airbnb as the style guide, and JSON as the file format. You can change these configurations according to your project)

after following the above steps a file named `eslintrc.json` should be created with the following code (will be auto-generated according to the configuration made above) 

![eslintrc configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rcgirmnrvmvpn2nc8daw.png)
that object of `rules:{}` is where you can put your own rules if you want to but for now, we are using Airbnb rules as mentioned in `"extends": ["plugin:react/recommended", "airbnb"]`
For more on eslint rules you can check their official site [here](https://eslint.org/docs/rules)

**4. Installing Prettier dependencies**
prettier is an [opinionated] (https://stackoverflow.com/questions/802050/what-is-opinionated-software#:~:text=Opinionated%20software%20is%20built%20and,for%20which%20it%20was%20developed.) code formatter that styles code consistently and is easier to use. it supports HTML, CSS, Javascript, and most of their libraries

run this command to install prettier (as a dev dependency) 
note that `--save-exact` ensures that everyone will install the same version of prettier to avoid inconsistency
```
npm install --save-dev --save-exact prettier
```
**5. Configure Prettier**
- in the root folder create a file named `.prettierrc.json` this will contain custom rules/options that you may want prettier to follow while formatting your code. enter the following code in your `.prettierrc.json`

```javascript
{
	"tabWidth": 2,
	"useTabs": true,
	"printWidth": 80,
	"semi": true,
	"trailingComma": "es5",
	"singleQuote": true,
	"endOfLine": "lf"
}
```
you can learn more about these prettier rules and more [here](https://prettier.io/docs/en/options.html)

**6. Integrating Prettier with ESLint**
As mentioned above we will be using Eslint as our linter and prettier as our code formatter. Linters usually contain not only code quality rules, but also stylistic rules. Most stylistic rules are unnecessary when using Prettier, but worse – they might conflict with Prettier! so to use them both safely we had to install `eslint-config-prettier` dependency

run the following command
```
npm install --save-dev eslint-config-prettier
```
- `eslint-config-prettier`: Turns off all eslint rules that are unnecessary or might conflict with Prettier. to make sure that eslint only check code syntax style while Prettier check code formatting
- to configure `eslint-config-prettier` in your `.eslintrc.json` extent prettier **add it as last** like following

```javascript
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["plugin:react/recommended", "airbnb", "prettier"],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {
  }
}
```
**7. Configure scripts**
to be able to run ESLint and Prettier we need to add scripts in our `package.json` as the following

```javascript
	"scripts": {
                ... // other scripts you have
		"lint": "eslint . --fix --max-warnings=0",
		"format": "prettier . --write"
	},
```
- `"lint": "eslint . --fix --max-warnings=0"`: this script runs eslint from the root folder and auto fix error and checks that we don't have any warning
- `"format": "prettier . --write"`: this script will run prettier from the root folder and auto fix format errors

**8. Installing Husky**
Husky is a tool that allows us to work with Git hooks. Git hooks are scripts that you can set up to run at certain events in the Git lifecycle. like before every commit or push. In our case, we will be using Husky to run ESlint and Prettier as our pre-commit hook so that no one will be able to commit when their code doesn't follow our rules.

creating pre-commit and configuring Husky can be challenging to set up and share across the team therefore we will be using a tool called `lint-staged` that installs Husky and set up everything for you and you only specify scripts to run on every commit 
the best part is that with `lint-staged` we save time by only checking staged(changed) files since we don't want to check in every file if we didn't edit them

Make sure your folder is a git directory 

run the following command to install lint-staged
```
npx mrm@2 lint-staged
```
a folder called `husky` will be created including different files as mentioned below

![husky folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atiw8mjidw7axnwghb18.png)
- the command `npx lint-staged` in the pre-commit file means that on every commit git will run scripts in the lint-staged command in `package.json`
- if you open `package.json` you will notice that `lint-staged` entry was added at the bottom like the following

```javascript
	"lint-staged": {
		"*.js": "eslint --fix ",
		"*.{js,css,md,html,json}": "prettier --cache --write"
	}
```
by calling `npx lint-staged` these commands in this lint-staged object will be triggered and for all `.js` we would run eslint and on all `.js,.css,.md` (you can even add `html`, `json` if you have any) we would run prettier 

- we can even run the scripts that we configured earlier like the following

```javascript
	"lint-staged": {
		"*.js": "npm run lint",
		"*.{js,css,md,html,json}": "npm run format"
	}
```
**9. Try committing**
After setting up eslint prettier and husky on every commit we will run `lint` script to check errors and `format` script to format our code if any error is found the commit process will be aborted
currently with code from article one if try to commit with `git commit` I get the following lint errors

![lint errors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3fqy78sfaqvdannghjq.png)
The Airbnb style we are using require that you write React code in files with `.jsx` extensions not `.js` that's why Eslint is crying. you can either fix these errors or disable the rules 
you can learn more about disabling eslint rules [HERE](https://eslint.org/docs/user-guide/configuring/rules)

To fix the particular errors in the image above we can rename all files that have `jsx` to have `.jsx` extension and make sure we update everywhere those files are referenced from `.js` to `.jsx`
run `npm run start` to make sure everything still works as expected

**10. Bonus**
for better experience, if you are using VSCode you can install ESLint and Prettier extension that will work better with the above configuration 

There you have it! you just configured Eslint prettier and Husky in a node project next time you have a team or an open-source project your code quality will be ensured. I will see you in a next one

For references you can get code mentioned in this article from this [GitHub repository](https://github.com/Yvad60/blog-code-references/tree/setup-eslint-prettier-and-husky)