Setting up Eslint & Prettier for your React App
There are many tools that allow you to write high-quality code such as Eslint and Prettier. Find out how to integrate them in your React Application.
Install Eslint
Format and set some rules by an eslintrc file (which can be a js, json, etc)
- Install the the eslint package
npm i eslint -D
- Then you can set your eslint config by initialize from CLI, so you can run
npx eslint --init
# or you can do the same with
./node_modules/.bin/eslint --init
- Then choose your best options that tailored to your project
- You should see a new eslintrc file generated with some configs
- If you want to fix and format your code, you run
npx eslint . --fix
- In case you don't want to remember this command, you can add it to your scripts in package json
..
eslint: "eslint . --fix"
..
Add your config in vs code
"editor.codeActionsOnSave": {
"source.fixAll.eslint": false
},
"editor.formatOnSave" : true,
"editor.defaultFormatter" : "esbenp.prettier-vscode"
Install Prettier
npm i prettier eslint-config-prettier -D
Create your prettier file config pretiterrc.json
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
}
Add prettier plugin in eslint config (always to the right)
{
"plugins": ["prettier"],
"rules" : {
"prettier/prettier" : "error"
}
}
Install lint stages (similar to husky)
npx mrm lint-staged