Add Eslint To Angular 12 Project

9 min read Oct 09, 2024
Add Eslint To Angular 12 Project

Adding ESLint to Your Angular 12 Project

ESLint is a powerful tool for enforcing consistent code style and catching potential errors in your JavaScript code. It's a valuable asset for any Angular project, especially for large or collaborative teams. This article will guide you through the process of integrating ESLint into your Angular 12 project.

Why Use ESLint?

1. Consistency and Code Quality: ESLint helps you enforce a consistent coding style across your project, making it easier to read and maintain. 2. Early Error Detection: ESLint can identify potential issues in your code before you even run your application, saving you time and effort in debugging. 3. Improved Code Maintainability: By catching style violations and potential bugs early, ESLint makes it easier to work with your codebase and reduces the chance of introducing new errors.

Steps to Integrate ESLint into Your Angular 12 Project

1. Install Necessary Packages:

npm install -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

This command installs the core ESLint package, the TypeScript parser, and the TypeScript-specific ESLint plugin.

2. Configure ESLint:

Create a new file named .eslintrc.json at the root of your Angular project. This file will contain your ESLint configurations. Here's a basic example:

{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "createDefaultProgram": true,
    "project": "tsconfig.json"
  },
  "plugins": [
    "@typescript-eslint",
    "prettier"
  ],
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  "rules": {
    "@typescript-eslint/no-unused-vars": "warn",
    "prettier/prettier": "warn"
  }
}

Explanation:

  • root: Set to true to indicate that this is the root of your ESLint configuration.
  • parser: Specifies the TypeScript parser.
  • parserOptions: Provides additional options for the parser. project points to your TypeScript configuration file.
  • plugins: Includes the TypeScript and Prettier plugins.
  • extends: Extends existing ESLint configurations.
  • rules: Defines custom rules.

3. Install Prettier for Code Formatting:

npm install -D prettier

Prettier is a code formatter that can help you maintain consistent code formatting and improve code readability.

4. Configure Prettier:

Create a .prettierrc.json file in your project's root directory. Here's an example:

{
  "printWidth": 120,
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "bracketSpacing": true,
  "arrowParens": "always"
}

This configuration sets various formatting preferences for your code.

5. Configure Angular CLI to use ESLint:

Open your angular.json file and modify the linter section in the build target:

  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "outputPath": "dist/your-app-name",
      "index": "src/index.html",
      "main": "src/main.ts",
      "polyfills": "src/polyfills.ts",
      "tsConfig": "tsconfig.app.json",
      "aot": true,
      "assets": [
        "src/favicon.ico",
        "src/assets"
      ],
      "styles": [
        "src/styles.css"
      ],
      "scripts": [],
      "vendorChunk": true,
      "extractLicenses": false,
      "optimization": true,
      "outputHashing": "all",
      "sourceMap": false,
      "extractCss": true,
      "namedChunks": false,
      "buildOptimizer": true,
      "budgets": [
        {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
        },
        {
          "type": "anyComponentStyle",
          "maximumWarning": "6kb",
          "maximumError": "10kb"
        }
      ],
      "serviceWorker": false,
      "ngswConfigPath": "ngsw-config.json",
      "inlineStyleLanguage": "scss",
      "lint": [
        {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        {
          "builder": "@angular-eslint/builder:lint",
          "options": {
            "lintFilePatterns": [
              "src/**/*.ts",
              "src/**/*.tsx",
              "src/**/*.html"
            ]
          }
        }
      ]
    },
    "configurations": {
      "production": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
          }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "extractLicenses": true,
        "buildOptimizer": true,
        "budgets": [
          {
            "type": "initial",
            "maximumWarning": "500kb",
            "maximumError": "1mb"
          },
          {
            "type": "anyComponentStyle",
            "maximumWarning": "2kb",
            "maximumError": "5kb"
          }
        ]
      },
      "development": {
        "buildOptimizer": false,
        "optimization": false,
        "vendorChunk": true,
        "extractLicenses": false,
        "sourceMap": true,
        "namedChunks": true
      }
    },
    "defaultConfiguration": "production"
  },

6. Add ESLint to the Angular CLI's ng lint command:

ng add @angular-eslint/schematics

This command will update your Angular CLI configuration to integrate ESLint.

7. Run ESLint:

You can now run ESLint on your project by executing the following command:

ng lint

This will run ESLint against your codebase and report any errors or warnings.

8. Integrate ESLint with Your IDE:

Most popular IDEs, such as Visual Studio Code, have built-in support for ESLint. Configure your IDE to use your .eslintrc.json file and you'll see real-time error and warning feedback as you write your code.

Tips for Using ESLint in Your Angular Project

  • Create Custom Rules: You can define your own custom rules to enforce specific coding standards specific to your project.
  • Use ESLint Plugins: Numerous ESLint plugins exist to enhance your code analysis, such as plugins for accessibility, security, or performance.
  • Integrate with Code Review: Set up your code review workflow to automatically check for ESLint errors and warnings.
  • Avoid Overly Strict Rules: Start with a moderate set of rules and gradually increase the strictness as your team becomes more comfortable with ESLint.
  • Consider using a linter for HTML: You can also use ESLint for linting your HTML files, but it is recommended to consider specialized HTML linters like htmlhint or eslint-plugin-html.

Conclusion

Adding ESLint to your Angular project significantly improves your code quality, reduces errors, and helps maintain consistent coding styles. This investment in code analysis will pay dividends in the long run, making your project easier to maintain and extend. Remember to experiment with different rules and plugins to tailor your ESLint configuration to your specific needs.