Index

配置解析器

你可以使用自定义解析器将 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";
import { defineConfig } from "eslint/config";

export default defineConfig([
	{
		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";
import { defineConfig } from "eslint/config";

export default defineConfig([
	{
		languageOptions: {
			parser: babelParser,
			parserOptions: {
				requireConfigFile: false,
				babelOptions: {
					babelrc: false,
					configFile: false,
					presets: ["@babel/preset-env"],
				},
			},
		},
	},
]);