Eslint允许基于glob模式使用多个解析器

9

我目前使用的 eslint 解析器是 @typescript-eslint/parser,我想要使用需要 babel-eslint 解析器的 @babel/plugin-proposal-optional-chaining 插件。

我看到过 eslint-multiple-parsers,但它已经被弃用了:请使用基于 glob 模式的 ESLint 配置(overrides)。请参阅https://eslint.org/docs/user-guide/configuring/#configuration-based-on-glob-patterns

我该如何设置多个解析器?


1
这里也遇到了与@angular-eslint/template-parser@html-eslint/parser相关的问题。我唯一能想到的解决方法是使用两个不同的ESLint配置文件运行两个命令。但可悲的是,我找不到同时将这两种解析器引入我的代码编辑器的解决方案。 - DerZyklop
2个回答

16

基于glob模式的配置

与任何其他ESLint配置几乎相同,特定于glob的配置可以包含覆盖块,其中可以包含除root和ignorePatterns之外的任何有效配置选项。

在您的eslint配置文件中,您可以添加一个overrides部分,它是一个对象数组。每个对象都必须具有files键,在其中定义了glob模式。任何匹配的文件都将使用覆盖的配置。例如:

{
    // estree parser
    "env": {
        "es6": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:security/recommended"
    ],
    "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "plugins": [
        "security"
    ],
    "rules": {
        "indent": [ "error", 4 ]
    },
    // rest of your "normal" configuration here

    "overrides": [{
        // for files matching this pattern
        "files": ["*.ts"],
        // following config will override "normal" config
        "parser": "babel-eslint",
        "parserOptions": {
            // override parser options
        },
        "plugins": [
            "@babel/plugin-proposal-optional-chaining"
        ],
        "rules": [
            // override rules
        ],
    },
    }]
}

然而,如果你已经使用了@typescript-eslint/parser,那么你可能已经匹配了*.ts文件,覆盖它只会使每个*.ts文件都使用babel-eslint,这并不能解决你的问题。

我假设你想让两个解析器(typescript-eslint和babel)同时运行在同一个文件上,但我不知道一个简单的解决方案。


2

你的目标是对文件X运行解析器A,对文件Y运行解析器B吗?

@enterthenamehere-bohemian’s anwser是解决方案。

您的目标是同时对同一文件运行两个解析器吗?

这取决于……

您的eslint是否在编辑器中运行?

截至今天,我看不到单个eslint配置文件内的解决方案。如果您想在编辑器中运行它,您需要一个单独的配置文件。

您的eslint是否在命令行或持续集成环境中运行?

您需要三个配置文件。

文件.eslintrc.json

{
    "parser": "@typescript-eslint/parser",
    "extends": ["./eslint-common-rules.json"],
    "rules": {
        …typescript parser rules here
    }}

文件 .eslintrc.babel.json
{
    "parser": "babel-eslint",
    "extends": ["./eslint-common-rules.json"],
    "rules": {
        …babel parser rules here
    }}

文件 eslint-rules.json

{
    "rules": { … 
        …common eslint rules here
    }}

有了这个,你可以在命令行中运行:

eslint # <- runs .eslintrc.json
eslint --config .eslintrc.babel.json

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接