How to Configure ESLint with Prettier in React Project

ESLint with Prettier in React App

Install ESLint and Prettier

Many modern JavaScript Projects use ESLint with Prettier setup. While ESLint keeps the style in good shape, Prettier is used to autoformate the code. In this article we will show our approach to setting up a React project with ESLint and Prettier (AirBnB). Let’s create a project and name it eslint-prettier-airbnb

npm init -y

Install prettier and eslint into your project

yarn add prettier eslint --dev

Also, install Prettier and ESLint extension/plugin for your editor/IDE. For instance, in VSCode you can find Prettier and ESLint extensions on their marketplace. It should be quite similar for your IDE/editor of choice. Most IDEs can be configured to run ESLint and Prettier on save so you wont need to run it manually.

Install two more packages which are in charge of combining ESLint with Prettier:

yarn add eslint-config-prettier eslint-plugin-prettier --dev

Now it is time to do some configuration. Run the command below.

npx eslint --init

Choose the answers below to the prompted questions

  • Check syntax, find problems, enforce style
  • JavaScript modules
  • React
  • (Does your project use typescript) No
  • Browser
  • Use a popular style guide
  • Airbnb
  • JSON
  • (Install dependencies?) Yes

After dependencies are installed. Update .eslintrc.json too look like this. Feel free to make changes to this file to accommodate your projects needs.

// .eslintrc.json
{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:react/recommended",
        "airbnb",
        "prettier"
    ],
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react", "prettier"
    ],
    "rules": {
        "react/prop-types": 0,
        "prettier/prettier": [
          "error",
          {
            "endOfLine": "auto"
          }
        ],
        "arrow-body-style": "off",
        "prefer-arrow-callback": "off"
      }
}

There maybe instances where you would like to change Prettier settings. You can use .prettierrc file for that. Here is more information on how to do that.

As far as we concerned, we are done. If you would like to learn how to install React project with Webpack please continue reading.

Bonus: Install React with Webpack

Install react, react-dom, and react-router-dom

yarn add react react-dom react-router-dom

Install webpack, webpack-cli, and webpack-dev-server

yarn add webpack webpack-cli webpack-dev-server@^3.11.2 --dev

Now let’s create webpack.config.js file in the root of our project and add the following code:

// webpack.config.js
/* eslint-disable no-unused-vars */
const path = require('path')
const webpack = require('webpack')
const { HotModuleReplacementPlugin } = require('webpack')
const Dotenv = require('dotenv-webpack')

module.exports = {
  entry: ['react-hot-loader/patch', path.resolve(__dirname, './src/index.js')],
  plugins: [new Dotenv()],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader'
      },
      {
        test: /\.s[ac]ss$/i,
        loader: 'style-loader'
      },
      {
        test: /\.s[ac]ss$/i,
        loader: 'css-loader',
        options: {
          modules: {
            mode: 'local',
            auto: true,
            exportGlobals: true,
            localIdentName: '[name]__[local]--[hash:base64:5]',
            localIdentContext: path.resolve(__dirname, 'src'),
            exportLocalsConvention: 'camelCase',
            exportOnlyLocals: false
          }
        }
      },
      {
        test: /\.s[ac]ss$/i,
        loader: 'sass-loader'
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader'
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
    alias: {
      components: path.resolve(__dirname, 'src', 'components')
    }
  },
  output: {
    path: path.resolve(__dirname, 'dist/'),
    publicPath: '/dist/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: path.join(__dirname, 'public/'),
    historyApiFallback: {
      index: 'index.html'
    },
    port: 3030,
    publicPath: 'http://localhost:3030/dist/',
    hotOnly: true
  }
}

Let’s also add .babelrc file and put the following configuration in there as well:

// .babelrc
{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": ["react-hot-loader/babel", "@babel/plugin-transform-runtime"]
}

Now we have to install all the dependencies that we are using and add run scripts to package.json file.

yarn add dotenv-webpack react-hot-loader babel-loader style-loader css-loader sass-loader file-loader @babel/preset-env @babel/preset-react react-hot-loader/babel @babel/plugin-transform-runtime --dev

Add public folder to the root of your project and put index.htm file with the following content:

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React Webpack Starter App</title>
  </head>
  <body>
    <div
      id="app"
    ></div>
    <noscript> Please enable javascript to view the site </noscript>
    <script src="../dist/bundle.js"></script>
  </body>
</html>

Create src folder with the following files and the content below: index.js, App.jsx, App.scss, _variables.scss

// src/index.js
import React from 'react'
import ReactDOM from 'react-dom'

import App from './App.jsx'

const element = document.getElementById('app')

ReactDOM.render(<App />, element)
// src/App.jsx
import React from 'react'
import { hot } from 'react-hot-loader/root'
import './App.scss'

const App = () => {
  return (
    <>
      <h1>{process.env.APP_NAME}</h1>
      <p>Hello world</p>
    </>
  )
}

export default hot(App)
// src/App.scss
@import './variables';

#app {
    background-color: $facebook;
}
// src/_variables.scss
$facebook: #3b5998;
$twitter: #1da1f2;
$google: #d44a36;
$shopify: #50b83c;

Create .env file in the root of your project.

# .env
APP_NAME="React Webpack Starter App"

Finally your package.json file should look something like this:

{
  "name": "react-webpack-starter-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "npx webpack-dev-server --hot --mode development",
    "build": "npx webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/plugin-transform-runtime": "^7.14.5",
    "@babel/preset-env": "^7.14.7",
    "@babel/preset-react": "^7.14.5",
    "babel-loader": "^8.2.2",
    "css-loader": "^6.0.0",
    "dotenv-webpack": "^7.0.3",
    "eslint": "^7.30.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-config-standard": "^16.0.3",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-promise": "^5.1.0",
    "eslint-plugin-react": "^7.24.0",
    "file-loader": "^6.2.0",
    "node-sass": "^6.0.1",
    "prettier": "^2.3.2",
    "react-hot-loader": "^4.13.0",
    "sass-loader": "^12.1.0",
    "style-loader": "^3.1.0",
    "webpack": "^5.45.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.2"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0"
  }
}

You are all set. Run

yarn dev

and visit http://localhost:3030 The app will automatically reload when you make changes. Happy coding!

Related posts:

Logger Setup with Winston

Share this article

Posted

in

by

Tags: