乐闻世界logo
搜索文章和话题

How to configure @typescript-eslint rules

1个答案

1
  1. Install Dependencies

First, ensure that your project has the necessary packages installed:

bash
# Using npm npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin # Or using yarn yarn add --dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

These packages include ESLint itself, the TypeScript ESLint parser (which enables ESLint to understand TypeScript syntax), and the TypeScript ESLint plugin (which provides a set of ESLint rules specifically designed for TypeScript code).

  1. Configure ESLint

Create an .eslintrc configuration file or add an eslintConfig field in package.json. In this configuration, specify the parser and the plugins and rules you want to enable. For example:

json
{ "parser": "@typescript-eslint/parser", "plugins": [ "@typescript-eslint" ], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "rules": { "@typescript-eslint/rule-name": "error" } }

Here:

  • "parser": "@typescript-eslint/parser" specifies that ESLint uses @typescript-eslint/parser as the parser.
  • "plugins": ["@typescript-eslint"] adds the TypeScript ESLint plugin.
  • "extends": ["plugin:@typescript-eslint/recommended"] inherits a set of recommended rules from the TypeScript ESLint plugin.
  • "rules": {} allows you to override specific rule settings. You can set it to "error" (to report errors when issues occur), "warn" (to issue warnings when issues occur), or "off" (to disable the rule).
  1. Customize Rules

For example, if you want to configure the no-unused-vars rule to avoid warnings for unused variables while allowing unused function parameters, set it as follows:

json
{ // ...other configuration "rules": { "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }] } }

In this example, "argsIgnorePattern": "^_" allows you to declare parameters starting with _, even if they are unused, so ESLint will not issue warnings.

  1. Use ESLint in Your Project

Finally, run ESLint on your TypeScript files from the command line:

bash
eslint yourfile.ts

Or, add a script to your package.json for easy execution:

json
{ "scripts": { "lint": "eslint . --ext .ts,.tsx" } }

Then, run the following command to check your project:

bash
npm run lint

Ensure that your TypeScript configuration file tsconfig.json is located in the project root directory, as the TypeScript ESLint parser requires it to correctly parse TypeScript code.

This covers the basic steps to configure @typescript-eslint rules. You can adjust the rules based on your project needs; for better code quality, it is recommended to follow the recommended rule set provided by the @typescript-eslint plugin.

2024年6月29日 12:07 回复

你的答案