Setting up eslint for react

banner for the post
Goal: Setup linting for any react projects.

A linter helps to automatically check your code for programatic errors and inconsistencies with the coding style. This ensures that the style of the code remains uniform throughout the project. It is a good practice to setup linting when working as a group in a project.

Instructions

Assumption: Already have node.js and npm installed.
  1. Create the boilerplate code for a react project.

     npx create-react-project eslint-tutorial
     cd eslint-tutorial
    
  2. Install eslint and intialize eslint in the project.

     npm install eslint --save-dev
     npx eslint --init
    

    Choose the following options:

    1. How would you like to use ESLint: To check syntax, find problems, and enfore code style
    2. What type of modules does your projects use? JavaScript modules (import/export)
    3. Which framework does your project use? React
    4. Does your project use TypeScript? No
    5. Where does your code run? Browser
    6. Which style guide do you want to follow? Airbnb
    7. What format fo you want your config file to be in? JSON

    options

  3. Add the following lines to the rules in the .eslintrc.json

         "rules": {
             "react/jsx-filename-extension": [
                 1,
                 {
                     "extensions": [
                         ".js",
                         ".jsx"
                     ]
                 }
             ],
             "no-unused-vars": "warn",
             "import/prefer-default-export": 0
         }
    
  4. Add the jest to the environment.

     "env": {
         "browser": true,
         "es2021": true,
         "jest": true
     }
    
  5. Update the settings.json in your vscode. (Optional)

     "editor.formatOnSave": true,
     "editor.codeActionsOnSave": {
         "source.fixAll.eslint": true
     },
     "eslint.alwaysShowStatus": true,
     "files.autoSave": "onFocusChange",
     "eslint.validate": [
         "javascript"
     ],
    
    
  6. Add the following lines to the package.json.

     "lint": "eslint src/**/*.js",
     "lint:fix": "eslint src/**/*.js --fix"
    
  7. Finally, to enforce the linting style to the changes made in the codebase.

     npm run lint:fix
    

Resources

  • GitHub Repository