Setup ESLint and Prettier VS Code extensions for React app
Automate javascript file formatting
Introduction
This is a quick beginner's guide to setup ESLint and Prettier in VS Code. This guide only covers installing VS Code extensions and editor settings. The following are the benefits for setting up your code editor:
- Both ESLint and Prettier are pluggable extensions
- Increases productivity by enabling automatic formatting
- Reduces chances of potential bugs
- Helps in writing clean and readable code
ESLint
ESLint is a javascript linter. It is a static code analyzer that helps in identifying problematic patterns in your code. For example, one popular ESLint rule is no-unused-vars which ensures there are no unnecessary variable declarations. With no-unused-vars, the code below would be incorrect:
You have to just remove the declaration for variable "x" to correct it:
Prettier
Prettier is a opinionated code formatter. It parses the code and automatically reprints it according to the coding style such as maximum length of line and wrapping the code when necessary.
Prerequisites
The following are the prerequisites for this setup:
- VS Code is already installed.
- [OPTIONAL] Create a new React app using
create-react-app
. This is the easiest way to start a new React project.
NOTE: You can try out the editor settings with your existing JS projects as well.npx create-react-app my-react-app cd my-react-app npm start
Setup automatic file formatting in VS Code
Follow the steps below to install and setup ESLint and Prettier in VS Code:
- Install ESLint and Prettier VS Code extensions.
- Open editor settings and enable Format On Save.
On Windows/Linux: File > Preferences > Settings
On macOS: Code > Preferences > Settings
Learn more about VS Code settings here .or you can put the line mentioned below in settings.json.
{ // Other configuration "editor.formatOnSave": true, }
- Add the following configuration in your settings.json to format javascript files.
{ // Other configuration "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode", }, }
- Now, try to format any javascript file and check.