ReactSensei

Add Prettier and ESLint to VS Code with Create React App

May 03, 2020

  1. 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

  1. Install the following VS Code Extensions

  2. Create the Prettier and ESLint Configuration files
  3. 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"
}
  1. Apply Prettier formatting on Save (Optional but recommended)
  2. 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
  1. Prevent Prettier Violations from being Committed (Optional but recommended)
  2. 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
  3. 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
  1. Test it out
  2. You should see your React code format on save
  3. Add to GitHub and it will auto format before committing code

Reference


© 2020