Website logo

13 Dec 2017

ESLint
and
Prettier
is
a
Best
Match

Sometimes you confused by the bugs in your code caused by missing semicolon or importing the wrong packages. You can spend minutes or hours just to find it. Especially if your code is not beauty and hurt your eyes. If it happens, you should fell in love with ESLint and Prettier.

ESLint is a tools which allows developers to discover problems with their Javascript code without executing it. Problem example are like missing semicolon, too much indentation, import non-exisiting packages, unused variables and etc. It will mark the problem with red underline.

ESLint is very customizable. You can choose and use existing linting rules, choose popular style, or create your own. The top 3 popular style is Standard, Google and AirBnB.

And in the other side, Prettier is a code formatter which can make your code looks beautiful. It removes all original styles of your code and transform it into beauty form. It has support for Javascript, JSX, Flow, Typescript, CSS, LESS, SCSS, JSON, GraphQL and Markdown.

Setup

Let's install ESLint and Prettier from command line first.

npm install --save-dev eslint prettier

And for this case, we setup ESLint and choose popular style provided by AirBnB.

./node_modules/.bin/eslint --init

Installing ESLint and Prettier

After that, we should integrate Prettier with ESLint.

npm install --save-dev eslint-plugin-prettier

Sometimes, there is a formatting issue conflict where ESLint and Prettier has a different preference. You should disable the conflicting rules and still keeping other rules where Prettier doesn't care.

Let's install eslint-config-prettier to solve it.

npm install --save-dev eslint-config-prettier

Edit file .eslintrc.json like below.

{
  "extends": [
    "airbnb-base",
    "prettier"
  ],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}

Okay, we will use Visual Studio Code as our text editor and integrate with it. You can download it here and then install ESLint and Prettier as extensions from it marketplace.

ESLint extension in VSCode

Prettier extension in VSCode

Usage

And now we can try it. First, there are several mistakes which break the rules in example code.

Unused variables

Using single quotes

Now you can press Ctrl + Shift + I, and Voila ! the code looks more beautiful than before. (The red underline still appear because there are unused variables exists and non-existing package imported).

Formatted with Prettier

Conclusion

As you know, ESLint and Prettier are the best tools which make the developer more fun to code and stop worrying about the code style and missing packages.