Write cleaner code using Prettier and ESLint in VSCode
A short and simple tutorial to help you configure Prettier and ESLint to work together in VSCode.
ESLint is the one of the most widely-used linting tools in web development. It’s an invaluable tool for keeping your (and your team’s) code consistent by ensuring everyone is following the same style conventions. ESLint is often configured to run during a Git hook to avoid allowing commits or pushes with code that violates the style guidelines.
But finding out that you have ESLint warnings to resolve when you’re ready to commit is annoying. Why not let VSCode give us real-time ESLint warnings? That way, when we commit, we already know that our code will pass the linter.
First, you should have ESLint installed globally.
Depending on your package manager, run
yarn global add eslint
or
npm install --global eslint
Next, install the ESLint extension for VSCode:
- (Cmd+Shift+X / Ctrl+Shift+X) to open Extensions panel.
- Search the Marketplace for ‘eslint’ and install the extension.
- Reload VSCode and watch the linter warnings appear:
Bam! Now, we get instant feedback whenever we write code that violates our style guide’s rules. This tutorial assumes that your project already has an .eslintrc configuration file. If present, the editor extension will read its rules from that file. If not, I assume it applies some default config.
We can do better.
VSCode is now showing us all of our ESLint warnings. But we still have to correct them manually. Boo! To make life easier on ourselves, let’s install another tool called Prettier. Prettier will auto-format our code for us when we ask it to or when we save a file.
To install:
yarn global add prettier
or
npm install --global prettier
We also need to install an extension for VSCode to make it work in the editor. Install Prettier — Code formatter from the VSCode extension marketplace:
With Prettier installed, we can auto-format a file or a selection by using the Command Palette option Format Document. Alternatively, we can utilize the shortcut combos Shift+Option+F / Shift+Alt+F.
We’re not quite finished yet. Prettier comes with a default configuration which probably won’t agree with the ESLint configuration that our project is using. Watch what happens when Prettier and ESLint aren’t using the same style rules:
Fortunately, there is an easy solution to this problem!
- Open the User Settings screen in VSCode (Cmd + , / Ctrl + ,)
- Set prettier.eslintIntegration to true.
- Optional — set formatOnSave to true if you want Prettier to format your files whenever you save.
Now watch as Prettier auto formats out code using our ESLint configuration rules:
tl;dr
- Install
eslint
andprettier
globally using yarn or npm. - Install ESLint and Prettier VSCode Extensions
- In VSCode User Settings, set "
prettier.eslintIntegration": true
- Optionally, set “
editor.formatOnSave":true
I hope this helps and is easy to follow! Please leave comments/questions/corrections!