配置解析器

你可以使用自定义解析器将 JavaScript 代码转换为抽象语法树,供 ESLint 评估。如果你的代码与 ESLint 的默认解析器 Espree 不兼容,你可能想要添加自定义解析器。

¥You can use custom parsers to convert JavaScript code into an abstract syntax tree for ESLint to evaluate. You might want to add a custom parser if your code isn’t compatible with ESLint’s default parser, Espree.

配置自定义解析器

¥Configure a Custom Parser

在许多情况下,你可以使用 ESLint 附带的 默认解析器 来解析 JavaScript 代码。你可以选择使用 parser 属性覆盖默认解析器。parser 属性必须是符合 解析器接口 的对象。例如,你可以使用 @babel/eslint-parser 包来允许 ESLint 解析实验性语法:

¥In many cases, you can use the default parser that ESLint ships with for parsing your JavaScript code. You can optionally override the default parser by using the parser property. The parser property must be an object that conforms to the parser interface. For example, you can use the @babel/eslint-parser package to allow ESLint to parse experimental syntax:

// eslint.config.js
import babelParser from "@babel/eslint-parser";

export default [
    {
        files: ["**/*.js", "**/*.mjs"],
        languageOptions: {
            parser: babelParser
        }
    }
];

此配置确保使用 Babel 解析器而不是默认的 Espree 解析器来解析所有以 .js.mjs 结尾的文件。

¥This configuration ensures that the Babel parser, rather than the default Espree parser, is used to parse all files ending with .js and .mjs.

已知以下第三方解析器与 ESLint 兼容:

¥The following third-party parsers are known to be compatible with ESLint:

配置解析器选项

¥Configure Parser Options

解析器可以接受选项来改变它们的行为方式。languageOptions.parserOptions 用于将选项直接传递给解析器。这些选项始终是特定于解析器的,因此你需要检查正在使用的解析器的文档以获取可用选项。下面是为 Babel ESLint 解析器设置解析器选项的示例:

¥Parsers may accept options to alter the way they behave. The languageOptions.parserOptions is used to pass options directly to parsers. These options are always parser-specific, so you’ll need to check the documentation of the parser you’re using for available options. Here’s an example of setting parser options for the Babel ESLint parser:

// eslint.config.js
import babelParser from "@babel/eslint-parser";

export default [
    {
        languageOptions: {
            parser: babelParser,
            parserOptions: {
                requireConfigFile: false,
                babelOptions: {
                  babelrc: false,
                  configFile: false,
                  presets: ["@babel/preset-env"]
                }
            }
        }
    }
];
ESLint 中文网
粤ICP备13048890号