ESLint and Prettier for a better team collaboration

May 29, 2018

When we work in a team of developers we all have our way of programming which may end up with an archaeology type of codebase, where we can guess who has written which part just by the way the code is formatted. You get distracted when you read the code due to a stylistic difference, and you lose time in PRs for nitpicking feedback. The code is also harder to maintain since you may end up with Git diffs related only to formatting. For these reasons, it’s important to share the same coding style.

Luckily the process of making sure that all code follows the same style is easily automated. Linting and formatting before committing the code ensure that it looks the same, no matter who writes it.

At Acast, we have decided to use ESLint coupled with Prettier. ESLint is a JavaScript linting and style checking tool that warns you when your code is not following given rules, but it doesn’t reformat your code. That’s where Prettier comes into play. Prettier is a fantastic tool that entirely takes the responsibility to format your code. It’s opinionated which means it has only a few settings you can customise. Moreover, it is well integrated with ESLint, so it’s possible to run Prettier via eslint --fix command, which reduces the number of commands that you have to run to lint and format the codebase. Additionally, we chose to use the ESLint config from Airbnb because it’s popular amongst the JavaScript community and to avoid lengthy discussions around what rules we should define in our config. We want to override as few rules as possible to avoid entering lengthy debates loop for little reward.

How to use it.

To include it into your project, you can check the README file in the eslint-config-acast project or do these two steps:

Install the needed packages:

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

Create a .eslintrc file and add the following to it:

{
  "extends": "acast"
}

And you are good to go!

Automate all the things!

To be able to lint your changes before committing I recommend to use lint-staged and husky. They allow you to run npm tasks on Git hooks events, in our case in precommit hook.

npm install --save-dev husky lint-staged

In your package.json:

{
  "scripts": {
    "lint": "eslint --max-warnings=0",
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.js": ["npm run lint"]
  }
}

Now, every time you commit a change, lint-staged runs npm run lint task on JavaScript files that have been staged and if there is an error, the commit is aborted*.

* Unfortunately, there is an issue on lint-staged when you partially stage files which prevent us to reformat and stage the changes automatically. You may need to check issues reported by ESLint when your commit has been aborted.


Written by Antoine Lehurt (a.k.a kewah). Front-end developer living in Stockholm and currently working at Acast. You should follow him on Twitter.