Codebrahma

Work

ESLint Setup for React Projects: Step-by-Step

ESLint is a crucial tool for React developers to maintain code quality and catch errors early. Here's a quick guide to set it up:

  1. Install ESLint and React plugins
  2. Create .eslintrc.json config file
  3. Set parser options for modern React code
  4. Add npm scripts for easy linting
  5. Configure your code editor (e.g., VSCode)
  6. Run your first lint check
  7. Fix common errors and warnings

Key benefits:

  • Keeps code consistent
  • Catches errors before they happen
  • Enforces React best practices
  • Customizable to fit your team's needs

Quick setup:

npm install eslint eslint-plugin-react eslint-plugin-react-hooks --save-dev

Create .eslintrc.json:

{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended"
  ],
  "plugins": ["react", "react-hooks"],
  "parserOptions": {
    "ecmaVersion": 2021,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  }
}

Add to package.json:

"scripts": {
  "lint": "eslint \"src/**/*.{js,jsx}\"",
  "lint:fix": "eslint \"src/**/*.{js,jsx}\" --fix"
}

Run npm run lint to check your code or npm run lint:fix to auto-fix issues.

Before You Start

Let's get your React project ready for ESLint. Here's what you need to do:

Node.js and npm

Node.js

First, make sure you have Node.js and npm. These are must-haves for managing packages and running JavaScript.

Check if you've got them:

node --version
npm --version

See version numbers? You're set. If not, grab the latest stable version from the Node.js website.

React Project Setup

Got Node.js? Great. Now let's set up a basic React project:

npx create-react-app my-react-app
cd my-react-app

This creates a new React app with a standard structure:

What Why
src/ Your React components and main app logic
public/ Static assets and main HTML file
package.json Project dependencies and scripts
node_modules/ Installed npm packages

Linting 101

Before we dive into ESLint setup, let's cover the basics:

  • A linter checks your code for errors and style issues without running it.
  • Rules tell ESLint what to look for in your code.
  • Configuration is how you set up ESLint for your project.

Now, let's add ESLint to your project:

npm install eslint eslint-plugin-react eslint-plugin-react-hooks --save-dev

This installs ESLint and React-specific plugins.

"ESLint looks at your code without running it. It's like a spell-checker, but for code."

ESLint is flexible. You can tweak it to match your team's coding style.

With this groundwork, you're ready to set up ESLint for your React project. This prep work will make the rest of the setup smooth sailing.

Basic Setup Steps

Let's get ESLint up and running for your React project. Here's how:

Install ESLint

ESLint

First, grab ESLint and the React plugins:

npm install eslint eslint-plugin-react eslint-plugin-react-hooks --save-dev

This adds ESLint and React-specific plugins to your project's dev dependencies.

Create Config File

Next, make an .eslintrc.json file in your project's root. Drop in this config:

{
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended"
  ],
  "plugins": ["react", "react-hooks"],
  "parserOptions": {
    "ecmaVersion": 2021,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

This sets up ESLint with recommended rules for JavaScript and React, including hooks.

Add React Plugins

We've already installed the React plugins. Here's what they do:

  • eslint-plugin-react: Catches React-specific issues
  • eslint-plugin-react-hooks: Makes sure you're using hooks correctly

These plugins are key for spotting React-related problems early.

Set Parser Options

Our config includes these parser options:

"parserOptions": {
  "ecmaVersion": 2021,
  "sourceType": "module",
  "ecmaFeatures": {
    "jsx": true
  }
}

This tells ESLint to:

  • Use ECMAScript 2021 features
  • Treat files as ES modules
  • Allow JSX syntax

These settings help ESLint understand modern React code.

To make ESLint easy to use, add these scripts to your package.json:

"scripts": {
  "lint": "eslint \"src/**/*.{js,jsx}\"",
  "lint:fix": "eslint \"src/**/*.{js,jsx}\" --fix"
}

Now you can run npm run lint to check your code or npm run lint:fix to auto-fix issues.

"ESLint is a must-have for React developers. It keeps your code clean and helps you catch mistakes early." - Jacob Isah, Author

That's it! You've set up ESLint for your React project. This setup will help you write cleaner, more consistent React code by catching common errors and enforcing best practices.

Main Settings

Let's dive into the key ESLint settings that'll boost your React development workflow.

Use Ready-Made Configs

ESLint offers pre-made configs to save time and promote best practices. Here's a solid starting point for React projects:

{
  "extends": [
    "eslint:recommended",
    "plugin:import/errors",
    "plugin:react/recommended",
    "plugin:jsx-a11y/recommended"
  ],
  "plugins": ["react", "import", "jsx-a11y"]
}

This setup extends recommended ESLint rules, adds import checking, and includes React and accessibility-specific rules.

Set Up Environments

Tell ESLint where your code runs:

"env": {
  "browser": true,
  "es2021": true,
  "node": true
}

This lets ESLint understand browser globals, ES2021 features, and Node.js environments.

Set Basic Rules

Here are some key rules for React projects:

"rules": {
  "react/prop-types": 0,
  "indent": ["error", 2],
  "linebreak-style": 1,
  "quotes": ["error", "double"]
}

This config:

  • Turns off prop-types checking (handy for TypeScript users)
  • Enforces 2-space indentation
  • Warns about inconsistent line breaks
  • Requires double quotes for strings

Choose Rule Levels

ESLint has three rule enforcement levels:

Level Meaning Use Case
"off" or 0 Rule is off For rules not applicable to your project
"warn" or 1 Treated as warning For non-critical issues to be aware of
"error" or 2 Treated as error For must-fix critical issues

For example:

"rules": {
  "no-console": "warn",
  "react/jsx-key": "error",
  "no-unused-vars": "error"
}

This warns about console usage, errors on missing keys in lists, and flags unused variables as errors.

Pick Files to Check

Specify which files ESLint should check. Add this to your package.json:

"scripts": {
  "lint": "eslint \"src/**/*.{js,jsx}\"",
  "lint:fix": "eslint \"src/**/*.{js,jsx}\" --fix"
}

This tells ESLint to check all .js and .jsx files in the src directory and its subdirectories. The lint:fix command tries to automatically fix issues where possible.

"ESLint's flexibility allows teams to tailor their linting rules to their specific needs, ensuring consistent code quality across projects." - Tim William James, Full-Stack Software Engineer

ESLint's customizable nature lets you fine-tune your setup to match your team's coding standards and project requirements.

sbb-itb-cc15ae4

Connect with Dev Tools

Let's set up ESLint with your dev tools. We'll focus on Visual Studio Code (VSCode), a popular choice for React developers.

Add npm Commands

First, add these scripts to your package.json:

"scripts": {
  "lint": "eslint . --ext .js,.jsx",
  "lint:fix": "eslint . --ext .js,.jsx --fix"
}

Now you can run npm run lint to check your code or npm run lint:fix to fix issues automatically.

Set Up in VSCode

Here's how to get ESLint working in VSCode:

  1. Install the ESLint extension from the VSCode marketplace.
  2. Open your project in VSCode.
  3. Add this to your settings.json:
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": ["javascript", "javascriptreact"]
}

This setup runs ESLint every time you save, helping you catch issues early.

Enable Auto-Fix

Want ESLint to fix simple issues automatically when you save? Here's how:

  1. Open VSCode settings.
  2. Search for "ESLint".
  3. Check "ESLint: Auto Fix on Save".

Or, add this to your settings.json:

"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true
}

Live Error Checking

The VSCode ESLint extension checks for errors as you type. You'll see:

Indicator Meaning
Red underline Error
Yellow underline Warning
Green underline Info

Hover over underlined code to see the ESLint message and possible fixes.

"Having lint rules run every time you save your work can be more reliable." - DigitalOcean Author

With this setup, you'll catch and fix issues faster, making your React coding smoother and more efficient.

Testing and Fixes

Let's put your ESLint setup to the test and iron out any wrinkles. Here's how to check your setup, run your first code check, and tackle common issues.

Check Your Setup

Got Visual Studio Code? Here's a quick way to verify ESLint:

  1. Hit Ctrl + Shift + U to open the Output tab.
  2. Pick "ESLint" from the dropdown.

You should see something like this:

[Info  - 3:31:54 PM] ESLint server is starting
[Info  - 3:31:55 PM] ESLint server running in node v14.16.0
[Info  - 3:31:55 PM] ESLint server is running.

No dice? Double-check your ESLint installation and VSCode extension.

First Code Check

Time to run your first lint. Open your terminal and type:

npm run lint

This checks all .js and .jsx files in your src/ directory, including subdirectories. ESLint will show any issues in the terminal.

Want to check a specific file? Try:

npx eslint src/SignupButton.js

Fix Common Errors

Hit some snags? Here's how to tackle common errors:

1. "React must be in scope when using JSX"

Using React 17 or later? Disable this rule in your .eslintrc.js:

"rules": {
  "react/react-in-jsx-scope": "off",
  "react/jsx-uses-react": "off"
}

For earlier versions, make sure you have import React from 'react'; at the top of your JSX files.

2. "'countItems' is never reassigned. Use 'const' instead"

Either change let to const if the variable isn't reassigned, or ignore the warning:

// eslint-disable-next-line
let countItems = 7;

3. Missing prop types

Not using PropTypes? Reduce the severity:

"rules": {
  "react/prop-types": "warn"
}

Pro tip: It's tempting to disable rules, but addressing the underlying issues often improves your code quality.

Fix Setup Problems

Stuck on setup? Try these:

1. Plugin conflicts

Seeing "Plugin 'react' was conflicted between 'package.json' and 'eslint-config-react-app'"? Try:

  • Use lowercase directory names (e.g., "react-app" not "React-App")
  • Downgrade eslint-config-react-app: yarn add --dev eslint-config-react-app@6
  • Remove and reinstall eslint-config-react-app

2. ESLint not running

If ESLint's MIA in your editor:

  • Check if the ESLint extension is installed and enabled
  • Verify your project has a valid ESLint config file
  • Restart your editor

3. Auto-fix not working

Add this to your VSCode settings:

"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true
}

"By addressing the issues highlighted by ESLint, we can ensure that our code adheres to best practices, is easier to read, and has fewer potential bugs." - Jacob Isah, React author

Don't sweat it if you hit some bumps. With these tips and a bit of persistence, you'll have a smooth ESLint setup for your React project in no time.

Custom Settings

ESLint's flexibility lets you tailor it to your React project. Here's how to customize ESLint for better performance and code quality:

Add More Rules

Want to beef up your linting? Try adding extra rule sets. For React, the eslint-plugin-react-perf plugin offers performance-focused rules.

Here's how to add it:

  1. Install the plugin:
npm i eslint-plugin-react-perf
  1. Add it to your ESLint config:
{
  "plugins": ["react-perf"],
  "extends": ["plugin:react-perf/recommended"]
}

This plugin includes rules like jsx-no-new-object-as-prop to prevent unnecessary re-renders. You can tweak it:

{
  "react-perf/jsx-no-new-object-as-prop": [
    "error",
    {
      "nativeAllowList": ["style"]
    }
  ]
}

This setup allows new objects for the style prop on native elements, balancing performance and flexibility.

Make Custom Rules

Need rules specific to your project? You can create custom ESLint rules.

To make a custom rule:

  1. Check the Abstract Syntax Tree (AST) of your target code.
  2. Define what your rule should catch.
  3. Write the rule logic.

Here's a basic custom rule structure:

module.exports = {
  meta: {
    type: "problem",
    docs: {
      description: "Prevent immediate format() call on Intl.DateTimeFormat",
    },
  },
  create(context) {
    return {
      MemberExpression(node) {
        // Rule logic here
      },
    };
  },
};

This rule could boost performance in date formatting operations.

Skip Certain Files

Want to exclude some files from linting? Use the .eslintignore file or the ignorePatterns option in your ESLint config.

Example .eslintignore:

build/*.js
config/*.js
node_modules/

Or in your ESLint config:

{
  "ignorePatterns": ["gulpfile.js", "webpack.config.js"]
}

This helps focus linting on your main React components and logic.

Speed Up ESLint

ESLint can slow down for big React projects. Here's how to speed it up:

  1. Enable caching: Add --cache to your ESLint command:
npx eslint --cache src/

This creates a .eslintcache file, making future runs faster.

  1. Find slow rules: Use the TIMING environment variable:
TIMING=1 npx eslint src/

You'll see output like this:

Rule                    | Time (ms) | Relative
:-----------------------|----------:|--------:
react/jsx-no-undef      |      80.0 |    53.3%
no-unused-vars          |      50.0 |    33.3%
react/jsx-uses-vars     |      20.0 |    13.3%
  1. Optimize slow rules: Based on these results, you might turn off or adjust time-consuming rules that aren't crucial for your project.

"Making custom ESLint rules isn't tough once you get the hang of it. It's a great way to enforce team-specific best practices." - Daria, Mews Developers

Wrap Up

Let's recap the key points of setting up ESLint for React projects and explore next steps to boost your development workflow.

Key Points Review

Here's a quick rundown of the main steps to integrate ESLint into your React projects:

  1. Install ESLint and React plugins
  2. Create an .eslintrc.json config file
  3. Set up parser options for modern React code
  4. Add npm scripts for easy linting
  5. Configure your code editor (like VSCode)
  6. Run your first lint check
  7. Fix common errors and warnings

ESLint isn't just a tool - it's a way to keep your code clean and your team productive. As Jacob Isah, a React expert, puts it:

"ESLint is an indispensable tool for React developers to maintain code quality and improve productivity."

What to Do Next

Want to level up your linting game? Here are some ideas:

1. Try more plugins

Look into performance-focused plugins like eslint-plugin-react-perf. They can help you spot potential slowdowns in your React components.

2. Tweak the rules

Make ESLint work for YOU. Adjust the rules to match your team's coding style. You might even create custom rules if you need something specific.

3. Add it to your CI/CD pipeline

Catch issues before they hit production by running ESLint checks as part of your continuous integration process.

4. Team up with Prettier

ESLint handles code quality, while Prettier takes care of formatting. Use both to keep your codebase consistent and clean.

5. Stay up-to-date

Don't let your ESLint setup gather dust. Update your config and plugins regularly to benefit from the latest best practices.

By following these steps, you'll catch bugs early and make it easier for your team to work together. As Tim William James, a full-stack dev from Canberra, says:

"By addressing the issues highlighted by ESLint, we can ensure that our code adheres to best practices, is easier to read, and has fewer potential bugs."

Written by
Anand Narayan
Published at
Nov 06, 2024
Posted in
Web Development
Tags
If you want to get more posts like this, join our newsletter

Join our NEW newsletter to learn about the latest trends in the fast changing front end atmosphere

Mail hello@codebrahma.com

Phone +1 484 506 0634

Codebrahma is an independent company. Mentioned brands and companies are trademarked brands.
© 2024 codebrahma.com. All rights reserved.