Automate ESLint and Prettier for your Next React Project!

Automate ESLint and Prettier for your Next React Project!

ยท

6 min read

ESLint and Prettier have saved me from the embarrassment of poorly formatted code. I have been using VS Code extensions for both, to lint and to format my code after each save.
But sometimes, I tend to ignore ESLint warnings, if, I am in a hurry or just simply lazy to be bothered and I end up pushing the buggy code to GitHub. After looking around for a bit, I found out that we can run ESLint and Prettier every time before committing staged files to avoid the buggy code and it is not that much of a stretch!

This is done with the help of a pre-commit hook provided by Git, that runs a defined set of commands every time when we commit our code.

๐Ÿ‹๐Ÿปโ€โ™€๏ธ Warm Up

I assume you already know about Git, GitHub, NPM Packages and the basics of React. It's great if you know about Git Hooks, but fine if you aren't aware of it.
Here is a brief information about the main sauce that we are going to use today:

ESLint

It is a tool for analyzing and identifying potential bugs or problematic patterns in JavaScript code. It's a highly customizable linting tool that allows developers to set rules and style guides according to their choice.

( ESLint Website | NPM | VS Code Extension )

Prettier

Prettier is considered as the opinionated code formatter that prettifies your code to look readable and eye-pleasing. It supports a ton of languages, tools and code editors and provides a wide range of variety for styling your code.

( Prettier Website | NPM | VS Code Extension | Online Playgroud )

Husky

Installing and configuring Git Hooks manually is a hell of a task. Husky(no, not ๐Ÿถ) helps us to work with hooks in a simple way. With the addition of just a few lines of code, husky is ready to work with client side git hooks like pre-commit.

( Husky Website | NPM )

Git Hooks

Git Hooks are predefined scripts that are executed whenever a particular event is triggered. We can customize Gitโ€™s internal behaviour and trigger customizable actions at key points in the development life cycle. There are two types of hooks - client side and server side. Here, we will be using a client side 'pre-commit' hook that allows us to perform a set of instructions before code is commited.

๐Ÿ‘ฉ๐Ÿพโ€๐Ÿ’ป Install packages

We need to install five packages manually. Other dependencies will be installed as we go.

npm i -D eslint prettier husky lint-staged eslint-config-prettier

Remember to save these packages as developer dependencies! We don't need any of these in production!!

Package NameDescription
eslintIdentifies potential bugs or problematic patterns in JS
prettierOpinionated code formatter that enforces a consistent style in codebase
huskyWorks with modern git hooks
lint-stagedRuns linter against staged files
eslint-config-prettierDisables ESLint rules related to code formatting, and only enables rules that detect potential bugs

๐Ÿงฎ Set up Eslint

To set up and configure ESLint, it is executed with the--init parameter to initialize the configuration and setup for the current project. You have to answer some questions to set up ESLint according to your need.
I have selected Airbnb as a style guide, but feel free to select your own style guide.

npx eslint --init

Answer to those questions like this: ESLint Init Demo GIF.gif

QuestionSelection
How'd you like to use ESLint?Enforce Style Guide
Type of modulesJavaScript
FrameworkReact
TypescriptNo
Where does your code run?Browser
Style GuideAirbnb
Config file formatJSON
Install additional pluginsYes

A configuration file named .eslintsrc.json is automatically generated when dependencies are installed.

Pre-bundles ESLint

create-react-app is already bundled with ESLint. If you ever open node_modules folder, you will see a bunch of dependencies and packages that are already installed.

But we need to ignore those to avoid conflicts with the one we just set up.
Remove eslintConfig from package.json so that react won't use pre-bundled dependencies anymore.

Ignoring files and folders

You can ignore specific files and folders from being checked and corrected by ESLint. Create a file named .eslintignore and add the following:

  1. node_modules
  2. build
  3. .git
  4. package-lock.json

Also, add any other configuration files that you might be using (tailwind, craco, etc).

At this point, you can check if ESLint is working by executing this command in the terminal:

npx eslint .

ESLint will display a list of warnings and errors categorized by files with the rule name. You can search the rule name online to understand more about it.

๐Ÿ’… Set up Prettier

Create a file in the root directory named .prettierrc. This is a configuration file stating prettier rules in JSON or YAML format.
You can learn more about prettier rules here but for now, paste this code in the configuration file:

{
  "semi": true,
  "tabWidth": 2,
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "none",
  "jsxBracketSameLine": true
}

๐Ÿ’ข Conflict between ESLint and Prettier

Now Prettier and ESLint are working with our project, but they are working independently. We need to tune them together so we can derive the most of them. Remember we installed eslint-config-prettier earlier? It would solve this problem. It automatically disables ESLint rules that might conflict with prettier settings. Ain't that great?

We just need to add prettier in our .eslintrc.json file as an extension:

{
  ...
  "extends": [
      "plugin:react/recommended",
      "airbnb",
      "prettier"
  ],
  ...
}

๐Ÿ”ง Configure Husky

We have installed lint-staged dependency earlier, now we need to configure it to add a pre-commit hook in our project. This will ensure linting is done to staged files before they are committed.

npx mrm@2 lint-staged

Once done, it will create a folder named husky in the root directory. This folder contains all the necessary information to run the pre-commit hook. If you check package.json, you will find a lint-staged key that will run ESLint and Prettier every time you commit the code.

You can add or remove extensions that are to be checked in the linting phase.

Verify

Well, it's done! Now your code will automatically be prettified after being checked for errors.
Create some errors intentionally - create unused variables or mess up the indentation and try committing the code.

OMG IT WORKSSSS.gif

๐ŸŽ‰Summing Up

Everything that I explained can be summarized like this:

  1. Install necessary packages.
  2. Initialize ESLint by executing npx eslint --init followed by answering a few questions.
  3. Create .eslintrc.json and .prettierrc to set up the configuration.
  4. Add node_modules and build and other production/ version control/ configuration files in .eslintignore file.
  5. Extend ESLint to use prettier.
  6. Configure husky.

Here are the resources if you wish to learn more about Git Hooks:

๐Ÿ‘‹ Conclusion

I was furious by manually running NPM scripts whenever I wanted to push my code, which led me to find a good solution that actually works. Hope this helped and saved your time. Let me know if it did - I am pretty active on Twitter and LinkedIn if you want to say hi!

Happy Linting! โš™

ย