I’ve gotten very used to having VSCode autoformat my file when I save. Usually, I use Prettier. But I joined a project that uses ESLint to manage its code style, and I wanted to match the team’s formatting.
I wanted that sweet auto-formatting on save, but using the eslintrc.json
file in the project’s root dir instead of Prettier.
Most blog posts wanted to make an entire tutorial out of this… how to set up eslint, how to create the .eslintrc file, etc etc… but I didn’t need that. I have an existing project, I just want to configure VSCode to use ESLint instead of Prettier.
This turned out to only need 4 lines of settings config and a plugin.
Here’s how to do it:
1. Install VSCode ESLint Plugin
In VSCode, open the extension browser with the button on the left. On the Mac, the keyboard shortcut Cmd+Shift+X should do the same.
Search for eslint
Install the top result, called “ESLint”. (It’s this one with over 10 million downloads)
2. Configure VSCode Settings to use ESLint for Formatting
Open up VSCode’s settings. On a Mac, press Cmd+,
or get there through the menus: Code > Preferences > Settings.
It’ll open the fancy settings editor, but we need the raw JSON settings file instead.
Click that tiny icon in the top-right that looks like a piece of paper with a little arrow.
Add these 4 new lines inside the top-level settings object:
{
// ...
"eslint.format.enable": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
The first one turns on ESLint for formatting, and the next 3 make it do the formatting when you hit save.
That should do it! Save the settings file and close it, we’re done.
Try making some changes to a file that violate some ESLint rule – maybe leaving off a semicolon if they’re required? – and pressing Save. It should auto-format.
Is the formatting still using Prettier?
I ran into a problem recently where Prettier settings were overriding the eslint settings. I’m honestly not sure how these got in there… maybe I put them in and forgot.
In any case, if you want ESLint to indent your files, make sure Prettier isn’t overriding it. Look for any lines like this, that say the defaultFormatter
should be Prettier (Cmd+F or Ctrl+F for “prettier” because there might be a few!), and comment them out:
// "[javascriptreact]": {
// "editor.defaultFormatter": "esbenp.prettier-vscode"
// },
You might need to undo this if you switch back to a project that doesn’t use ES Lint.
You can also create multiple VSCode profiles if you often work in projects with different requirements.