Add Prettier and ESLint to VS Code with Create React App
May 03, 2020
-
Install Prettier and the ESLint Plugin
- Note: You will need to install ESLint if you are not using Create React App
$ npm i -D prettier eslint-plugin-prettier
-
Install the following VS Code Extensions
- Create the Prettier and ESLint Configuration files
- note Make sure to create this file inside
React
app root
$ touch .eslintrc .prettierrc
.eslintrc
{
"extends": "react-app",
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
.prettierrc
- Will override default prettier settings and make all JavaScript files use single quotes instead of double quotes
{
"singleQuote": true,
"trailingComma": "es5"
}
- Apply Prettier formatting on Save (Optional but recommended)
- You most likely want to apply the Prettier formatting whenever you save your files. To do so, add the following to your Visual Studio Code Workplace Settings:
"editor.formatOnSave": true
- Prevent Prettier Violations from being Committed (Optional but recommended)
- To prevent unformatted code from being committed to Git you can add a pre-commit hook. There are a few ways to do this, I will show the steps using pretty-quick and husky setup (option 2). We’ll have gone with this option as pretty-quick respects the
.prettierrc
file - note: Your Git repository must already be initialized, otherwise the precommit hooks will not be installed by husky
Install the packages:
$ npm i -D pretty-quick husky
- Then add the husky section to your
package.json
file:
package.json
// MORE CODE
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
}
// MORE CODE
- Test it out
- You should see your React code format on save
- Add to GitHub and it will auto format before committing code