Using eslint and prettier to make your code perfect and beautiful and help you catch bugs while you're writing it
This doesn't work that well if we don't set up a node project first.
First, open up the homework folder in your text editor, not just the files individually. This is just because it makes life a lot easier, not necessarily because you need to (although... maybe you do?)
On the command line, cd
into the folder that your work is in. Or try using View > Terminal from the upper menu to make a terminal open up in VSCode.
Initialize a new npm project with npm init
. Just hit enter a hundred times until it stops asking you questions and creates a package.json
.
Install eslint, prettier, and the modules that let them work together like this:
npm i -D eslint prettier eslint-plugin-prettier eslint-config-prettier
npx install-peerdeps --dev eslint-config-standard
Your style rules live in a file called .eslintrc.json
. In class we let eslint
create one for us, but this time we're going to create the file on our own.
Save the JSON below as .eslintrc.json
in the root of your project folder (wherever you ran npm init
). Don't forget the period at the start of the filename.
{
"extends": ["standard", "prettier", "prettier/standard"],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"semi": false,
"printWidth": 80
}
]
}
}
You should have installed the ESLint VS Code plugin already. It'll work for all eslint projects. If you didn't install it, View > Extensions from the top menu, search for eslint, it's the first one.
If it's installed and you are in a node project with an .eslintrc.json
, you'll see squiggly lines on things it doesn't like. Hover over the lines and it'll explain what it's grumpy about.
If you want to manually autofix issues, you can use Cmd+Shift+P
to open the command palette and run ESLint: Fix all auto-fixable problems. I'm too lazy for that, though, and want it to happen automatically.
Open up the Settings menu (on OS X it's Code > Preferences > Settings) and search for eslint save
. Make sure Eslint: Auto Fix On Save is CHECKED and Editor: Format on Save is UNCHECKED.
Open a bad .js
file, Cmd+S
to save, and just like magic it'll be rewritten.