ESLint and Prettier working on Visual Studio Code with create-react-app

Kumar Saurav ๐Ÿ˜Ž
Screens
Published in
2 min readMar 27, 2018

Please visit updated version of this post

It can get a bit overwhelming when you are getting into react development with all the different tools and coding styles. Especially if you are coming from the native world like me. Should I use semicolon at the end of a line or not? Should I use a single quote or double quotes? These some of the few things a developer should be least worried about. But, javascript as it is, with the help of some tools, all these nuisances can be avoided.

ESLint is Javascript linter which can help in improving the code quality by identifying and reporting patterns in the code. Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary. Making them work together saves a lot of time for a developer.

This setup process will assume that we use create-react-app for creating a new react app.

Step 1

  • Install ESLint Visual Studio Code plugin by Dirk Baeumer
  • Install eslint globally
npm install eslint -g
  • Install Prettier Visual Studio Code plugin by Esben Petersen

Step 2

  • Add following dev dependencies
yarn add eslint-config-prettier eslint-plugin-prettier prettier  -D

Step 3

  • Create .eslintrc file in your root project folder
  • Add following lines to it
{
"extends": ["react-app", "plugin:prettier/recommended"]
}

Step 4

  • Update user settings of Visual Studio Code. Visual Studio Code settings can be invoked using Command + ,
  • And then add following lines
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false,
},
"prettier.disableLanguages": [
"js"
],
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true,
"files.autoSave": "onFocusChange"

This will make code formatting when saving a file or on changing focus.

Whenever you write a badly formatted code it will automatically be formatted when you save a file or switch from that file.

Step 5 Additional step to set up a pre-commit hook using husky, lint-staged and pretty-quick when you commit files.

  • install husky, lint-staged and pretty-quick as dev dependencies
yarn add husky lint-staged pretty-quick -D
  • add the line to package.json in the scripts section
"scripts": {
"precommit": "pretty-quick --staged"
}

Voila, it done now. Stop worrying about formatting the code, it will be automatically formatted for you when you save or commit your files.

--

--

Kumar Saurav ๐Ÿ˜Ž
Screens
Editor for

๐Ÿ‘จโ€๐Ÿ’ป Frontend Developer ๐ŸŒ ReactJS ๐Ÿ“ฑ Android โค๏ธDesign ๐ŸŽฎ PC Games ๐Ÿ‘ง Proud Father