How to integrate Eslint & Prettier in React
Create React App
to create react app you can use create-react-app package from npm so first thing to do is install it therefore start terminal and run below command.
sudo npm i -g create-react-app
Then to create app, run below command, take note it will create folder with the project name so you don’t need to do that.
now move in the folder and start the app using below command, take note you don’t need to run yarn or npm install as it already did for you.
yarn start or npm start
Install Eslint and Prettier
Second thing to do is installation so run below commands!
Eslint, it’s configuration by Airbnb and it’s required packages…
npm i -D eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
Prettier, it’s configuration to avoid conflict with Eslint and it’s required packages…
npm i -D prettier eslint-config-prettier eslint-plugin-prettier
Now to stop letting user committing 💩 into the repository we will install below packages.
npm i -D husky lint-staged pretty-quick
husky: Will run npm script before the committing the code.
lint-staged: Will run custom script on the filtered files by the extensions like .js or .jsx
pretty-quick: Will prettify your code.
Add scripts in Packages.json
Add below script in packages.json file.
Below script will run before commit and run our custom scripts lint-staged.
"precommit": "NODE_ENV=production lint-staged"
Below script will first run, pretty quick to format code if something does not on standard, then eslint will check the code agains the eslint rules and give errors if any came and stop commiting the code and finally adding files to stage so that it could be also be commit.
"eslint src/ --fix",
Set the Rules
Now everything is installed and setup, you need to setup the rules for both.
For eslint create .eslintrc file on the root and add below.
For Prettier create .prettierrc file on the root and add below.
All set now, you can play with code and see how this come out.
You can install extensions in your favourite IDE or code editor to highlight the eslint error and auto format the code accordingly to the rules you set.
My favourite is code editor is Visual Studio Code and this is how you can setup vscode.
First thing first to add support for Eslint and Prettier, you need to install below two extensions.
There are some settings you have to do for making these extensions workable.
Thank you very much for reading and don’t forget to clap if you like this tutorial, put some stars on the gist if you like those too.
I have recently uploaded my workshop videos on youtube about the freelancing using Upwork and Fiverr, here are the links.
Also I have done some open source projects, It’s highly appreciable if you try and give you feedback.
To know more about me checkout kamranqadri.me you can follow me and devncode here.