ESLint and Prettier for Angular
In web application development, using Angular as a reference framework, maintaining a clean, consistent and well-formatted code is crucial for the quality and maintainability of the project. Two tools to achieve this goal are ESLint and Prettier.
We will explain how to implement them in the Angular 18 projects.
What is ESLint and what is Prettier?
ESLint is a static code analysis tool focused on finding and correcting problems in JavaScript code and other JavaScript-based languages, such as TypeScript; it is used to maintain cleaner, more consistent and error-free code.
Prettier is a code formatting tool used to ensure that source code follows a consistent formatting style. It supports multiple programming languages and integrates easily with various development environments and text editors.
How do we install it?
First, we will have to go inside our Angular project through a terminal. And we will install ESLint by introducing the following command:
ng add @angular-eslint/schematics
We will see that two files have been modified and one has been added. The two modified files are package.json and angular.json; and the added eslint.config.js. But the two most important are package.json and eslint.config.js.
In the package.json the ESLint dependencies have been added and a new command has been created, which is the lint. With this command we will lint the whole project by typing the command ng lint in the terminal. And in the eslint.config.js where we will specify all the rules that will govern our project.
Second, we will install Prettier and we will do it by entering the following command:
npm install –save-dev –save-exact prettier
With this command we have added the Prettier dependency to our package.json. In order to set up our Prettier rules we will have to create the .prettierrc file in the root of the project (optional).
See the following link for the available Prettier rules.
Finally, to make Prettier work with ESLint, enter the following command in the terminal:
npm install –save-dev eslint-plugin-prettier eslint-config-prettier
Once installed, inside the eslint.config.js file, we will include the following as mentioned below:
const eslintPluginPrettierRecommended = require(‘eslint-plugin-prettier/recommended’);
module.exports = tseslint.config(
{…},
{…},
eslintPluginPrettierRecommended,
);
If we run ng lint we are likely to get multiple lint errors. If we want simple errors to be fixed quickly, we will type ng lint –fix; some of them may need to be manually modified by us.
Conclusions
Throughout the article we have installed ESLint and Prettier and made them work together using the ng lint command, as it is important to maintain standards within our projects in order to have clean, consistent and well-formatted code for the quality and maintainability of the project.