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

How to configure @ typescript -eslint rules

4 个月前提问
3 个月前修改
浏览次数38

1个答案

1

要配置 @typescript-eslint 规则,你需要按照以下步骤进行操作:

1. 安装依赖

首先确保你的项目中安装了必要的包:

bash
# 使用npm npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin # 或者使用yarn yarn add --dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

这些包包括 ESLint 本身、TypeScript ESLint 解析器(允许 ESLint 理解 TypeScript 语法),以及 TypeScript ESLint 插件(包含了一系列针对 TypeScript 代码的 ESLint 规则)。

2. 配置 ESLint

创建一个 .eslintrc 配置文件,或者在 package.json 中添加一个 eslintConfig 字段。在这个配置中,你需要指定解析器和想要启用的插件及其规则。例如:

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

在这里:

  • "parser": "@typescript-eslint/parser" 指定 ESLint 使用 @typescript-eslint/parser 作为解析器。
  • "plugins": ["@typescript-eslint"] 添加 TypeScript ESLint 插件。
  • "extends": ["plugin:@typescript-eslint/recommended"] 从 TypeScript ESLint 插件继承一系列推荐的规则。
  • "rules": {} 字段允许你覆盖特定的规则设置。你可以设置为 "error"(出现问题时报错),"warn"(出现问题时警告),或 "off"(关闭规则)。

3. 自定义规则

例如,如果你想要配置 no-unused-vars 规则,避免警告未使用的变量,但是允许声明未使用的函数参数,你可以这样设置:

json
{ // ...其他配置 "rules": { "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }] } }

在这个例子中,"argsIgnorePattern": "^_" 选项允许你声明一个参数以 _ 开头,即使它没有被使用,ESLint 也不会给出警告。

4. 在项目中使用 ESLint

最后,通过在命令行中运行 ESLint 来检查你的 TypeScript 文件:

bash
eslint yourfile.ts

或者,你可以添加一个脚本到你的 package.json 里面,以便轻松运行 ESLint:

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

然后,你可以通过运行以下命令来检查你的项目:

bash
npm run lint

确保你的 TypeScript 配置文件 tsconfig.json 也位于项目的根目录下,因为 TypeScript ESLint 解析器需要它来正确解析 TypeScript 代码。

以上就是配置 @typescript-eslint 规则的基本步骤。你可以根据你的项目需求调整规则,为了更好的代码质量,建议尽量遵循 @typescript-eslint 插件推荐的规则集。

2024年6月29日 12:07 回复

你的答案