All tech notes

Setup ESLint, Prettier, EditorConfig, and JSConfig in React Apps

A practical guide to configuring ESLint, Prettier, EditorConfig, and JSConfig in React projects to automate linting, code formatting, and import resolution.

Setup ESLint, Prettier, EditorConfig, and JSConfig in React Apps

Published June 12, 2021

Setup ESLint, Prettier, EditorConfig, and JSConfig in React Apps

Configure ESLint and Prettier to find errors and format your code.

Code Linting and Formatting Rules

Install the dependencies

Install these dependencies in your project using Yarn or NPM.

yarn add -D eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks prettier eslint-plugin-prettier
npm i -D eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks prettier eslint-plugin-prettier

ESLint configuration

Create .eslintrc in the project root directory. Paste the following configuration to customize your ESLint rules.

{
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "extends": [
    "plugin:react/recommended",
    "airbnb",
    "plugin:prettier/recommended"
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["react", "prettier"],
  "settings": {
    "react": {
      "version": "detect"
    },
    "import/resolver": {
      "node": {
        "moduleDirectory": ["node_modules", "src/"]
      }
    }
  },
  "rules": {
    "prettier/prettier": "error",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
    "react/jsx-filename-extension": "off",
    "import/no-unresolved": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "react/no-array-index-key": "off",
    "import/prefer-default-export": "off",
    "react/react-in-jsx-scope": "off",
    "no-plusplus": "off"
  }
}

Prettier configuration

ESLint and Prettier Editor Configuration

Create .prettierrc in the project root directory. Paste this code to configure Prettier formatting.

{
  "semi": true,
  "printWidth": 80,
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "all"
}

EditorConfig configuration

Create .editorconfig in the project root directory and paste this configuration.

root = true
 
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false

JSConfig configuration

Create jsconfig.json in the project root directory and paste this configuration.

{
  "compilerOptions": {
    "baseUrl": "src"
  }
}

Adding scripts in package.json

Add these scripts to package.json to run ESLint and Prettier easily.

{
  "scripts": {
    "escheck": "eslint .",
    "esfix": "eslint ./ --fix",
    "prettier": "prettier --write ."
  }
}

Related work

More tech notes