JavaScript 和 TypeScript 文件的不同 lint 规则
出现此问题的原因之一如下:
- 您使用的规则需要类型信息且未指定
parserOptions.project
;
- 您指定
parserOptions.project
,没有指定createDefaultProgram
(它将在未来的版本中删除),并且您正在检查项目中不包含的文件(例如babel.config.js
,metro.config.js
)
从TypeScript ESLint Parser 文档:
parserOptions.project
此选项允许您提供项目的tsconfig.json
. 如果要使用需要类型信息的规则,则需要此设置。
(...)
请注意,如果此设置已指定createDefaultProgram
但未指定,则您只能对项目中包含的文件进行 lint,这些文件由提供的tsconfig.json
文件定义。如果您现有的配置不包括您想要 lint 的所有文件,您可以创建一个单独的tsconfig.eslint.json
.
要解决它,请更新您的 ESLint 配置以仅在 TypeScript 文件上使用 TypeScript 规则:
{
// ...
parser: '@typescript-eslint/parser',
plugins: ["@typescript-eslint"],
overrides: [
{
files: ['*.ts', '*.tsx'], // Your TypeScript files extension
// As mentioned in the comments, you should extend TypeScript plugins here,
// instead of extending them outside the `overrides`.
// If you don't want to extend any rules, you don't need an `extends` attribute.
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
],
parserOptions: {
project: ['./tsconfig.json'], // Specify it only for TypeScript files
},
},
],
// ...
}
overrides
您可以在官方文档中阅读有关配置的更多信息:覆盖如何工作?
不要对特定文件进行 lint
如果您不想检查错误中提到的文件(例如babel.config.js
),您可以忽略它,将其名称添加到文件.eslintignore
中:
babel.config.js
无论如何,如果您的项目同时包含您想要 lint 的 JavaScript 和 TypeScript 文件,上述步骤(关于覆盖 TypeScript 文件的配置)很重要。
您还可以为不同的情况创建其他覆盖,例如测试文件的不同配置,因为它可以使用开发人员依赖项并在node
environment上运行,而不是browser
.