Using ESLint, Prettier and Typescript in a Nodejs project
Formatting code and adhering to style guides bring a considerable improvement in quality for our projects. As well said by Bob Martin, the ratio of time spent reading code versus writing is well over 10 to 1.
Besides better reading, it also helps the team work more concise and fewer changes appearing in the code reviews, letting us focus on what really matters.
This guide is focused on nodejs projects using typescript and adherent to the Airbnb style guide but can be adapted for other scenarios.
I’ll put here the step by step creating a new project (for clarity), but it can be easily adapted to change old projects as well (just skip the sections you already know)
PS: I also recommend the start of unit tests with jest up front, but I’ll not put this part here to make it more focused.
Starting a new typescript nodejs project
Starting from the basics, in a new folder run npm init -y to generate the package.json file
npm init -y
Install the typescript and typescript node definitions as dev dependencies:
npm i -D typescript @types/node
Add a tsconfig.json file
A critical part of this configuration is the version of the ECMAScript version you are setting as a target. Different browser versions or, in our case, nodejs versions support different ECMAScript versions. To check the versions (and features) supported by each nodejs version you can use this site: https://node.green/
Setting the ESLint for the project
Disclaimer: There are several ways, plugins, and packages to configure linting in your project. I’m going to describe here the minimal configuration, but I recommend you to see what is essential or not for you. Go to the npm website and see what the plugin does, what rules it enforces, and if it is critical or not for you.