我的“.eslintrc.js”文件出错 - “解析错误:已为@typescript-eslint/parser 设置了“parserOptions.project”。

Jam*_*mes 4 typescript eslint

ESLint 似乎无法解析“.eslintrc.js”文件

重现步骤:我建立了一个新的“hello world”TypeScript 项目,如下所示:

# Make a new directory for our new project
mkdir test
# Go into the new directory
cd test
# Create a "package.json" file
npm init --yes
# Install TypeScript
npm install typescript --save-dev
# Install ESLint (the linter)
npm install eslint --save-dev
# Install the Airbnb ESLint config (the most popular linting config in the world)
npm install eslint-config-airbnb-typescript --save-dev
# The import plugin for ESLint is needed for the Airbnb config to work properly with TypeScript
npm install eslint-plugin-import@^2.22.0 --save-dev
# The TypeScript plugin for ESLint is needed for the Airbnb config to work properly with TypeScript
npm install @typescript-eslint/eslint-plugin@^4.2.0 --save-dev
# Create the config file for TypeScript
touch tsconfig.json
# Create the config file for ESLint
touch .eslintrc.js
# Create the entry point for our TypeScript application
touch main.ts
Run Code Online (Sandbox Code Playgroud)

我用以下(空白/默认配置)填充“tsconfig.json”文件:

{}
Run Code Online (Sandbox Code Playgroud)

我在“.eslintrc.js”文件中填写以下内容,如Airbnb文档中所述

module.exports = {
  extends: ['airbnb-typescript/base'],
  parserOptions: {
    project: './tsconfig.json',
  },
};
Run Code Online (Sandbox Code Playgroud)

我用以下内容填充“main.ts”:

const foo = 'bar';
Run Code Online (Sandbox Code Playgroud)

然后,当我运行时npx eslint main.ts,它正确生成以下错误:

  1:7  error  'foo' is assigned a value but never used  @typescript-eslint/no-unused-vars
Run Code Online (Sandbox Code Playgroud)

因此,ESLint 似乎工作正常。但是,当我运行时npx eslint .eslintrc.js,出现以下错误:

  0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: .eslintrc.js.
The file must be included in at least one of the projects provided
Run Code Online (Sandbox Code Playgroud)

每当我打开“.eslintrc.js”文件时,VSCode 中也会出现此错误。需要解决该错误,以便 ESLint 可以对文件的其余部分进行 lint。(澄清一下,我希望“.eslintrc.js”文件以与我希望我的 TypeScript 源代码被 lint 相同的方式被 lint - 例如有 2 个空格缩进等等。)

附加信息:我使用的是带有 Node v14.8.0 和 npm 版本 6.14.7 的 Windows 10 LTSC。

Ret*_*sam 18

当您使用由 typescript 驱动的 eslint 规则时(当您的 eslint 配置包含一个"parserOptions.project"配置时),如果您尝试 lint 一个不是 typescript 项目中包含的文件之一的文件,eslint 会抛出错误。

这是由于性能原因 - 过去 eslint 允许这样做,但这样做会导致性能大幅下降,因此他们将其更改为引发错误

对不属于您的 TS 项目的文件进行 linting 的解决方案是创建一个 tsconfig 来扩展您的“真实” tsconfig,但包括您想要 lint 的所有文件。这通常被称为tsconfig.eslint.json,看起来像这样:

// Special typescript project file, used by eslint only.
{
    "extends": "./tsconfig.json",
    "include": [
        // repeated from base config's "include" setting
        "src",
        "tests",

        // these are the eslint-only inclusions
        ".eslintrc.js",
    ]
}
Run Code Online (Sandbox Code Playgroud)

而在你的.eslintrc.js你会改变project: './tsconfig.json'project: './tsconfig.eslint.json'

这应该可以解决错误并允许对.eslintrc.js文件进行检查。

  • 即使尝试执行上述步骤后,我仍然收到错误。 (3认同)