Antoine Lehurt

ESLint and Prettier for a better team collaboration

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 customize. 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:

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.js": ["eslint --fix", "git add", "eslint --max-warnings=0"]
  }
}

Now, every time you commit a change, lint-staged runs eslint against files that have been staged to fix formatting changes. Then, it stages them back and runs eslint again to detect other errors. The commit is aborted if there is an error.