ReactJs – Eslint

Recently i installed the Eslint on my project and it helps me to solve the problem quickly. Eslint useful to make your code more indented and you can define the rule to check your code base. Let me share the steps to setup the Eslint in your project. I am assuming you have already install the react project and now you are going to setup the eslint.

Step 1: Installing the Eslint
To install the eslint run the below commands

# npm -g i eslint-cli
# npm i eslint --save-dev

Step 2: Initialize the Eslint
To initialize the linter run the bellow command

# eslint --init  //For the Mac or Linux users
# node node_modules\eslint\bin\eslint.js --init //for windows users

Step 3: Configure the Eslint
During Step 2, you will get .eslintrc.json file where you defined the required parameter, now it’s the time to modify your linter file with your rules. I added the rule of ordering of import module in such a way to organize React first then 3rd party module then after internal modules. Please add the below code snippet inside your .eslintrc.json file

"import/order": [
            "error",
            {
                "groups": ["builtin", "external", "internal"],
                "pathGroups": [
                    {
                      "pattern": "react",
                      "group": "external",
                      "position": "before"
                    }
                ],
                "pathGroupsExcludedImportTypes": ["react"],
                "newlines-between": "always",
                "alphabetize": {
                    "order": "asc",
                    "caseInsensitive": true
                }
            }
        ]

To make the grouping you need to install one more plugin : “eslint-plugin-import” and you can install it via the below command

# npm install eslint-plugin-import --save-dev

After installation, you need to add the above p[lugin inside your .eslint plugin array as in below:

"plugins": [
        "react",
        "@typescript-eslint",
        "eslint-plugin-import"
    ],

Step 4: Configure package.json file
Now the time of magic, you need to setup the lint in your package.json file, as below

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "eslint src/**/*.tsx",
    "lint-fix": "eslint src/**/*.tsx --fix"
  },
// To get the list of error or warnings
# npm run lint
// To fix the issue from linter
# npm run lint-fix

That will help you to make your code more cleaner and compliant.

  • 23
    Shares