Setup ESLint + Prettier for your Drupal + React/TypeScript components

Learn how to improve the quality of your code with two powerful tools like ESLint and Prettier.

Giuseppe Iannì
Soulweb Academy
2 min readApr 5, 2021

--

Intro

In the previous article we have shown how to integrate a React / TypeScript component in Drupal 8. But what if we want also to Lint and Format our code?

Enter ESLint and Prettier.

ESLint

As you may already know, ESLint is a linter for Javascript code, or more specifically:

ESLint statically analyzes your code to quickly find problems.[…] Many problems ESLint finds can be automatically fixed. ESLint fixes are syntax-aware so you won’t experience errors introduced by traditional find-and-replace algorithms.”

Prettier

Prettier is an "opinionated code formatter" (sic.) that will help us to be sure that our code formatting follow standard rules - even if with customizable options.

The definition includes explicitly the word “opinionated” because — even in standards — there are variants and preferences, so we can carefully choose which features we want in our code ( trailing semicolon, single or double quotes, bracket spacing, etc.) and then be sure that everyone working on the project will produce their code accordingly.

Requirements

So, let’s start by adding the required packages to our component.

For Prettier:

Most of them are self-explanatory, it’s basically ESLint, Prettier, various style guides, and some plugins to make all of them work together with TypeScript.

We are installing them as devDependencies (--save-dev) since we only need them while we develop our component but we don't want them to be included in the final build.

Now, it’s time to create the .eslintrc.js file and add some configuration into it.

As you can see, there’s a line that refers to tsconfig.json, where we put the configuration for TypeScript (check our previous article).

Finally, we have to instruct our webpack to include the loaders for ESLint adding the following lines to the webpack.config.js file:

This will be the complete file afterwards:

Everything is pretty much done!

One more optional thing is to setup a command to our npm configuration to auto-format our code by adding a new line to our package.json in the scripts section.

Now, when we run the command $ npm run format the script will take care of reviewing and formatting all the .ts and .tsx.

Final thoughts

Even though they are not indispensable, it’s a very common choice to use tools like ESLint and Prettier on Javascript projects. On one hand, they help us to keep the code well-ordered and clean, on the other hand, it's a good way to auto-learn the coding standards and best practices.

--

--