Quick linting setup for a React web application
React + VSCode + ESLint
Quick Overview -
React A javascript library for building the user interface. Read more at - https://reactjs.org/
VSCode Visual Studio Code is a source-code editor developed by Microsoft for Windows, Linux, and macOS. It includes support for debugging, embedded GitHub, syntax highlighting and code intelligence. It also has installable extensions which add additional functionalities. Read more at - https://code.visualstudio.com/
ESLint It is a pluggable linting utility for Javascript which analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs. Read more at - https://eslint.org/
Steps for setup -
1)Let's use create react app (BoilerPlate) for creating the React application quickly in order to get the basic react app.
2)Delete below ESLint settings from the package.json file
eslintConfig:{
“extends”: “react-app”
}
3)Install ESLint extension for VSCode for enabling linting rule while coding. Use extension - https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint.
4)Run below command for installing ESLint as a dev dependency
npm i -D eslint
5)Run below command for installing ESLint rules for React as a dev dependency
npm i -D eslint-plugin-react
6)Create a .eslintrc file with below configs. This file is used by ESLint extension for linting the source code
{
"env": {
"browser": true,
"es6": true,
"jest": true
},
"parserOptions": {
"sourceType": "module"
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"rules": {
"indent": [
"error",
2
],
"react/jsx-equals-spacing": [
2,
"never"
],
}
}
Detail explanation of above file is -
env -Specify which environments you want to enable by setting each to true
browser -For browser global variables usage
es6 -For new ES6 global variables usage
jest -For Jest global variables usage. (For Unit Testing)
parserOptions -To specify the JavaScript language options you want to support
sourceType -For ECMAScript modules like import/export.
extends -To extend the set of enabled rules from base configurations
eslint:recommended -Adds recommended ESLint rules automatically by eslint library
plugin:react/recommended -Adds recommended react rules automatically by eslint-plugin-react library
rules - To add various rules against which VSCode runs the source code
7)Update VSCode user settings with below code available through ESLint extension
{
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true
}
autoFixOnSave -This will automatically fix the file as per the rules defined in .eslintrc file when user saves the file
alwaysShowStatus -VSCode runs eslint against the rules defined in .eslintrc file and show the status in problems tab
You can refer this https://github.com/harshmons/eslint-vscode-react as well for a complete setup