DEV Community

Cover image for Set up ESLint, Prettier and Husky in a React project | a step by step guide
Ivad Yves HABIMANA
Ivad Yves HABIMANA

Posted on • Updated on

Set up ESLint, Prettier and Husky in a React project | a step by step guide

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. 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. currently my folder structure looks like this

starting folder structure
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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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

follow this step to configure Eslint



npm init @eslint/config


Enter fullscreen mode Exit fullscreen mode

you will need to answer some questions about how you would like to use eslint follow the following configuration

ESLint configuration
(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
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

4. Installing Prettier dependencies
prettier is an opinionated 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


Enter fullscreen mode Exit fullscreen mode

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


{
    "tabWidth": 2,
    "useTabs": true,
    "printWidth": 80,
    "semi": true,
    "trailingComma": "es5",
    "singleQuote": true,
    "endOfLine": "lf"
}


Enter fullscreen mode Exit fullscreen mode

you can learn more about these prettier rules and more here

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


Enter fullscreen mode Exit fullscreen mode
  • 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


{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["plugin:react/recommended", "airbnb", "prettier"],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {
  }
}


Enter fullscreen mode Exit fullscreen mode

7. Configure scripts
to be able to run ESLint and Prettier we need to add scripts in our package.json as the following



    "scripts": {
                ... // other scripts you have
        "lint": "eslint . --fix --max-warnings=0",
        "format": "prettier . --write"
    },


Enter fullscreen mode Exit fullscreen mode
  • "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


Enter fullscreen mode Exit fullscreen mode

a folder called husky will be created including different files as mentioned below

husky folder structure

  • 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


    "lint-staged": {
        "*.js": "eslint --fix ",
        "*.{js,css,md,html,json}": "prettier --cache --write"
    }


Enter fullscreen mode Exit fullscreen mode

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


    "lint-staged": {
        "*.js": "npm run lint",
        "*.{js,css,md,html,json}": "npm run format"
    }


Enter fullscreen mode Exit fullscreen mode

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
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

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

Top comments (10)

Collapse
 
amir_gharajedaghi profile image
Amir

Good work as always.

Collapse
 
adeodatus profile image
Adeodatus Abdul

Thank you. you save my time

Collapse
 
sanket9006 profile image
Sanket Parshuram Patil

npx mrm@2 lint-staged
Running lint-staged...
Installing lint-staged and husky...
yarn add v1.22.19
[1/4] Resolving packages...
Couldn't find any versions for "lint" that matches "eslint . --fix --max-warnings=0"

Collapse
 
ivadyhabimana profile image
Ivad Yves HABIMANA • Edited

Hi @sanket9006 did you encounter the error when you were trying to install lint-staged (npx mrm@2 lint-staged) or when you ran the lint script (npm run lint)

Collapse
 
sanket9006 profile image
Sanket Parshuram Patil

@ivadyhabimana could you please help me here

Collapse
 
heero7 profile image
Kevin Mudiandambo

Solid article. Short and sweet!

Collapse
 
seungyn profile image
SeungYn

제 블로그에 해당 내용을 작성해도 될까요? Can I write that on my blog?

Collapse
 
ivadyhabimana profile image
Ivad Yves HABIMANA • Edited

Of course, feel free to do so. Please also cite the original version if someone needs to check it out as well

Collapse
 
mbanda1 profile image
Nixon

I remove eslintrc.yml, eslintignore, prettierignore and .prettierrc.json and my still able to run the script. I love it this way but i dont know how its running under box

Collapse
 
scottwright_dev profile image
Scott

Great tutorial much appreciated!