Skip to content

Latest commit

 

History

History
153 lines (107 loc) · 3.63 KB

README.md

File metadata and controls

153 lines (107 loc) · 3.63 KB

Angular + ESLint + Prettier

Introduction

This is a simple Angular project with Eslint and Prettier configured. The main goal is to have an Angular project with a good code style and format, and to achieve this, I use Eslint and Prettier together. I try to resume in simple steps how to configure it in a new Angular project. There are one branch for the result of each step, so you can see the changes in each one.

This project was generated with Angular CLI version 17.3.5 through the following command:

ng new --minimal --ssr=false --style=css --skip-git --skip-install angular-eslint-prettier

Table of contents

  1. Preparation
  2. Eslint
  3. Prettier
  4. Git hooks
  5. Recommended VSCode extensions

Preparation

Generate .nvmrc file with the Node version used in the project

node -v > .nvmrc

Use Node Version Manager for set Node version specified in .nvmrc file

nvm use

Install dependencies

npm install

Eslint

Add Angular Eslint Schematics to project

ng add @angular-eslint/schematics

For execute linting on all files you can use

npm run lint

Prettier

Add Prettier to project

npm install --save-dev --save-exact prettier

Add .prettierrc file to project root and the basic configuration suggested by Prettier is

{
  "trailingComma": "es5",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true
}

But, my personal preference is to use 2 spaces for indentation and trailing commas in all cases, so my .prettierrc file is

{
  "trailingComma": "all", // changed
  "tabWidth": 2, // changed
  "semi": false,
  "singleQuote": true
}

Install eslint-config-prettier to make ESLint and Prettier play nice with each other

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

Add eslint-config-prettier at the end of the extends array in your .eslintrc.json file

{
  "extends": ["...", "prettier"]
}

You can add a script to your package.json to run Prettier on all files ignoring unknown ones

{
  "scripts": {
    "format": "prettier --write --ignore-unknown --list-different ."
  }
}

And then run it with

npm run format

Git hooks

For check linting and formatting before commit you can use husky and lint-staged

npm install --save-dev husky lint-staged

The following init command simplifies setting up husky in a project. It creates a pre-commit script in .husky/ and updates the prepare script in package.json. Modifications can be made later to suit your workflow.

npx husky init

In file .husky/pre-commit replace the content with

npx lint-staged

Note: For CI environments, when install dependencies use npm ci --ignore-scripts to avoid prepare script execution

Add the following to your package.json file

{
  "lint-staged": {
    "**/*.{ts,html}": "npx eslint --fix",
    "**/*": "npx prettier --write --ignore-unknown"
  }
}

Note: It's important to run Prettier after ESLint

Recommended VSCode extensions