Index

Node.js API 参考

虽然 ESLint 被设计用于在命令行上运行,但也可以通过 Node.js API 编程方式使用 ESLint。Node.js API 的目的是允许插件和工具作者直接使用 ESLint 功能,而无需通过命令行接口。

🌐 While ESLint is designed to be run on the command line, it’s possible to use ESLint programmatically through the Node.js API. The purpose of the Node.js API is to allow plugin and tool authors to use the ESLint functionality directly, without going through the command line interface.

注意: 使用 API 中未记录的部分需自行承担风险。仅本文档中特别提到的部分被批准使用,并将保持稳定和可靠。任何未记录的部分都是不稳定的,可能随时发生更改或被移除。

ESLint 类

🌐 ESLint class

ESLint 类是在 Node.js 应用中使用的主要类。

🌐 The ESLint class is the primary class to use in Node.js applications.

这个类依赖于 Node.js 的 fs 模块和文件系统,所以你不能在浏览器中使用它。如果你想在浏览器中检查代码,请使用 Linter 类。

🌐 This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. If you want to lint code on browsers, use the Linter class instead.

这是一个使用 ESLint 类的简单示例:

🌐 Here’s a simple example of using the ESLint class:

const { ESLint } = require("eslint");

(async function main() {
	// 1. Create an instance.
	const eslint = new ESLint();

	// 2. Lint files.
	const results = await eslint.lintFiles(["lib/**/*.js"]);

	// 3. Format the results.
	const formatter = await eslint.loadFormatter("stylish");
	const resultText = formatter.format(results);

	// 4. Output it.
	console.log(resultText);
})().catch(error => {
	process.exitCode = 1;
	console.error(error);
});

这是一个自动修复 lint 问题的示例:

🌐 Here’s an example that autofixes lint problems:

const { ESLint } = require("eslint");

(async function main() {
	// 1. Create an instance with the `fix` option.
	const eslint = new ESLint({ fix: true });

	// 2. Lint files. This doesn't modify target files.
	const results = await eslint.lintFiles(["lib/**/*.js"]);

	// 3. Modify the files with the fixed code.
	await ESLint.outputFixes(results);

	// 4. Format the results.
	const formatter = await eslint.loadFormatter("stylish");
	const resultText = formatter.format(results);

	// 5. Output it.
	console.log(resultText);
})().catch(error => {
	process.exitCode = 1;
	console.error(error);
});

下面是使用 ESLint 类结合 lintText API 的示例:

🌐 And here is an example of using the ESLint class with lintText API:

const { ESLint } = require("eslint");

const testCode = `
  const name = "eslint";
  if(true) {
    console.log("constant condition warning")
  };
`;

(async function main() {
	// 1. Create an instance
	const eslint = new ESLint({
		overrideConfigFile: true,
		overrideConfig: {
			languageOptions: {
				ecmaVersion: 2018,
				sourceType: "commonjs",
			},
		},
	});

	// 2. Lint text.
	const results = await eslint.lintText(testCode);

	// 3. Format the results.
	const formatter = await eslint.loadFormatter("stylish");
	const resultText = formatter.format(results);

	// 4. Output it.
	console.log(resultText);
})().catch(error => {
	process.exitCode = 1;
	console.error(error);
});

◆ new ESLint(options)

const eslint = new ESLint(options);

创建一个新的 ESLint 实例。

🌐 Create a new ESLint instance.

参数

🌐 Parameters

ESLint 构造函数接受一个 options 对象。如果你省略了 options 对象,那么它将对所有选项使用默认值。options 对象具有以下属性。

🌐 The ESLint constructor takes an options object. If you omit the options object then it uses default values for all options. The options object has the following properties.

文件枚举

🌐 File Enumeration

  • options.cwd (string)
    默认值是 process.cwd()。工作目录。这必须是绝对路径。
  • options.errorOnUnmatchedPattern (boolean)
    默认值是 true。除非设置为 false,当未找到目标文件时,eslint.lintFiles() 方法会抛出错误。
  • options.globInputPaths (boolean)
    默认值是 true。如果存在 falseeslint.lintFiles() 方法不会解释通配符模式。
  • options.ignore (boolean)
    默认值是 true。如果存在 falseeslint.lintFiles() 方法不会遵循你配置中的 ignorePatterns
  • options.ignorePatterns (string[] | null)
    默认是 null。要忽略的文件模式,除了配置中忽略的之外也适用。这些模式是相对于 cwd 的。
  • options.passOnNoPatterns (boolean)
    默认值为 false。当设置为 true 时,缺失的模式会导致 lint 操作短路,并且不会报告任何失败。
  • options.warnIgnored (boolean)
    默认是 true。当文件列表包含被忽略的文件时显示警告。
代码检查

🌐 Linting

  • options.allowInlineConfig (boolean)
    默认值是 true。如果存在 false,ESLint 会在源代码中屏蔽指令注释。如果此选项为 false,它会覆盖配置中的 noInlineConfig 设置。
  • options.baseConfig (Config | Config[] | null)
    默认值是 null。[配置对象],由与此实例使用的所有配置扩展。你可以使用此选项定义默认设置,如果你的配置文件未进行配置,将使用这些默认设置。
  • options.overrideConfig (Config | Config[] | null)
    默认值为 null。[配置对象],在任何现有配置之后添加,因此在配置文件中包含的内容之后应用(如果使用)。
  • options.overrideConfigFile (null | true | string)
    默认值是 null。默认情况下,ESLint 会搜索配置文件。当此选项设置为 true 时,ESLint 不会搜索配置文件。当此选项设置为 string 值时,ESLint 不会搜索配置文件,并使用提供的值作为配置文件的路径。
  • options.plugins (Record<string, Plugin> | null)
    默认值是 null。ESLint 用于配置中 plugins 设置的插件实现。这是一个类似映射的对象。键是插件 ID,每个值是对应的实现。
  • options.ruleFilter (({ruleId: string, severity: number}) => boolean)
    默认值是 () => true。一个用于过滤要运行规则的谓词函数。该函数以一个包含 ruleIdseverity 的对象作为参数调用,如果该规则应运行,则返回 true
  • options.stats (boolean)
    默认是 false。当设置为 true 时,会在 lint 结果中添加额外的统计信息(参见 Stats 类型)。
自动修复

🌐 Autofix

  • options.fix (boolean | (message: LintMessage) => boolean)
    默认值是 false。如果存在 trueeslint.lintFiles()eslint.lintText() 方法在自动修复模式下工作。如果存在谓词函数,这些方法会将每条 lint 消息传递给该函数,然后仅使用函数返回 true 的 lint 消息。
  • options.fixTypes (("directive" | "problem" | "suggestion" | "layout")[] | null)
    默认是 nulleslint.lintFiles()eslint.lintText() 方法用于自动修复的规则类型。
缓存相关

🌐 Cache-related

  • options.cache (boolean)
    默认是 false。如果存在 trueeslint.lintFiles() 方法会缓存 lint 结果,并在每个目标文件未更改时使用该缓存。请注意,当你升级 ESLint 插件时,ESLint 不会清除缓存。在这种情况下,你必须手动删除缓存文件。即使你将 options.filePath 传递给方法,eslint.lintText() 方法也不会使用缓存。
  • options.cacheLocation (string)
    默认是 .eslintcacheeslint.lintFiles() 方法将缓存写入此文件。
  • options.cacheStrategy (string)
    默认是 "metadata"。用于检测已更改文件的缓存策略。可以是 "metadata""content"
抑制

🌐 Suppressions

  • options.applySuppressions (boolean)
    默认是 false。如果 true,抑制文件中的抑制会自动应用到 eslint.lintFiles()eslint.lintText() 的结果中。使用 eslint.lintText() 时,必须同时提供 filePath 选项,抑制才会生效。
  • options.suppressionsLocation (string)
    默认是 "eslint-suppressions.json"。抑制文件的路径。该路径可以是绝对路径,也可以相对于 cwd 的相对路径。
其他选项

🌐 Other Options

  • options.concurrency (number | "auto" | "off")
    默认是 "off"。默认情况下,ESLint 会检查调用线程中的所有文件。如果此选项指定了一个整数,ESLint 将使用最多该数量的工作线程并行检查文件。"auto" 会自动选择一个设置。当指定此选项时,所有其他选项必须是 可克隆的
  • options.flags (string[])
    默认值是 []。此实例要启用的功能标志。

◆ eslint.lintFiles(patterns)

const results = await eslint.lintFiles(patterns);

此方法检查与通配符模式匹配的文件,然后返回结果。

🌐 This method lints the files that match the glob patterns and then returns the results.

参数

🌐 Parameters

  • patterns (string | string[])
    要进行 lint 检查的目标文件。这里可以包含文件路径、目录路径以及通配符模式。

返回值

🌐 Return Value

  • (Promise<LintResult[]>)
    这个承诺将会以一个 LintResult 对象数组的形式实现。

◆ eslint.lintText(code, options)

const results = await eslint.lintText(code, options);

此方法检查给定的源代码文本,然后返回结果。

🌐 This method lints the given source code text and then returns the results.

默认情况下,此方法使用适用于当前工作目录中文件的配置(cwd 构造选项)。如果你想使用不同的配置,请传入 options.filePath,ESLint 将加载 eslint.lintFiles()options.filePath 文件中会使用的相同配置。

🌐 By default, this method uses the configuration that applies to files in the current working directory (the cwd constructor option). If you want to use a different configuration, pass options.filePath, and ESLint will load the same configuration that eslint.lintFiles() would use for a file at options.filePath.

如果 options.filePath 值被配置为忽略,则此方法返回一个空数组。如果同时设置了 options.warnIgnored 选项和 options.filePath 选项,则此方法返回一个 LintResult 对象。在这种情况下,结果可能包含一个警告,指出该文件已被忽略。

🌐 If the options.filePath value is configured to be ignored, this method returns an empty array. If the options.warnIgnored option is set along with the options.filePath option, this method returns a LintResult object. In that case, the result may contain a warning that indicates the file was ignored.

参数

🌐 Parameters

第二个参数 options 是可省略的。

🌐 The second parameter options is omittable.

  • code (string)
    要检查的源代码文本。
  • options.filePath (string)
    可选。源代码文本文件的路径。如果省略,result.filePath 将变为字符串 "<text>"
  • options.warnIgnored (boolean)
    可选,默认值为传递给构造函数的 options.warnIgnored。如果存在 trueoptions.filePath 是 ESLint 应忽略的文件,此方法将返回包含警告信息的 lint 结果。

返回值

🌐 Return Value

  • (Promise<LintResult[]>)
    该承诺将返回一个 LintResult 对象数组。使用数组(尽管只有一个 lint 结果)是为了保持此方法与 eslint.lintFiles() 方法之间的接口相似。

◆ eslint.getRulesMetaForResults(results)

const results = await eslint.lintFiles(patterns);
const rulesMeta = eslint.getRulesMetaForResults(results);

此方法返回一个对象,其中包含给定 results 中触发 lint 错误的每个规则的元信息。

🌐 This method returns an object containing meta information for each rule that triggered a lint error in the given results.

参数

🌐 Parameters

  • results (LintResult[])
    从调用 ESLint#lintFiles()ESLint#lintText() 返回的 LintResult 对象数组。

返回值

🌐 Return Value

  • (Object)
    一个对象,其属性名称是来自 results 的规则 ID,属性值是规则的元信息(如果可用)。

◆ eslint.calculateConfigForFile(filePath)

const config = await eslint.calculateConfigForFile(filePath);

此方法计算给定文件的配置,这对于调试目的很有用。

🌐 This method calculates the configuration for a given file, which can be useful for debugging purposes.

参数

🌐 Parameters

  • filePath (string)
    要计算其配置的文件路径。禁止使用目录路径,因为 ESLint 无法处理 overrides 设置。

返回值

🌐 Return Value

  • (Promise<Object>)
    将通过配置对象完成的承诺。

◆ eslint.findConfigFile(filePath)

const configFilePath = await eslint.findConfigFile(filePath);

此方法根据传递给构造函数的选项,找到该 ESLint 实例将使用的配置文件。

🌐 This method finds the configuration file that this ESLint instance would use based on the options passed to the constructor.

参数

🌐 Parameters

  • filePath (string)
    可选。要查找其关联配置文件的文件路径。如果省略,ESLint 将根据此实例的当前工作目录来确定配置文件。

返回值

🌐 Return Value

  • (Promise<string | undefined>)
    将被解析为所使用的配置文件的绝对路径,或者当没有使用配置文件时为 undefined(例如,当设置了 overrideConfigFile: true 时)。

◆ eslint.isPathIgnored(filePath)

const isPathIgnored = await eslint.isPathIgnored(filePath);

此方法检查给定文件是否被你的配置忽略。

🌐 This method checks if a given file is ignored by your configuration.

参数

🌐 Parameters

  • filePath (string)
    你想要检查的文件的路径。

返回值

🌐 Return Value

  • (Promise<boolean>)
    这个承诺将会根据文件是否被忽略而完成。如果文件被忽略,则会返回 true

◆ eslint.loadFormatter(nameOrPath)

const formatter = await eslint.loadFormatter(nameOrPath);

此方法加载一个格式化器。格式化器将 lint 结果转换为人类或机器可读的字符串。

🌐 This method loads a formatter. Formatters convert lint results to a human- or machine-readable string.

参数

🌐 Parameters

  • nameOrPath (string | undefined)
    你要检查的文件路径。允许以下值:
    • undefined。在这种情况下,加载 "stylish" 内置格式化器。
    • 内置格式化器 的名字。
    • 第三方格式化工具 的一个名称。例如:
      • "foo" 将加载 eslint-formatter-foo
      • "@foo" 将加载 @foo/eslint-formatter
      • "@foo/bar" 将加载 @foo/eslint-formatter-bar
    • 定义格式化程序的文件路径。路径必须包含一个或多个路径分隔符(/),以便区分它是否是路径。例如,以 ./ 开头。

返回值

🌐 Return Value

  • (Promise<LoadedFormatter>)
    将通过 LoadedFormatter 对象实现的承诺。

◆ eslint.hasFlag(flagName)

此方法用于确定是否设置了给定的功能标志,如以下示例所示:

🌐 This method is used to determine if a given feature flag is set, as in this example:

if (eslint.hasFlag("x_feature")) {
	// handle flag
}

参数

🌐 Parameters

  • flagName (string)
    要检查的标志。

返回值

🌐 Return Value

  • (boolean)
    如果标志已启用,则为真。

◆ ESLint.version

const version = ESLint.version;

ESLint 的版本字符串。例如,"7.0.0"

🌐 The version string of ESLint. E.g. "7.0.0".

这是一个静态属性。

🌐 This is a static property.

◆ ESLint.defaultConfig

const defaultConfig = ESLint.defaultConfig;

ESLint 内部使用的默认配置。这是为那些希望使用与 ESLint 相同默认值计算配置的工具提供的。请记住,默认配置可能会随版本变化,因此不应该依赖于任何特定的键或值的存在。

🌐 The default configuration that ESLint uses internally. This is provided for tooling that wants to calculate configurations using the same defaults as ESLint. Keep in mind that the default configuration may change from version to version, so you shouldn’t rely on any particular keys or values to be present.

这是一个静态属性。

🌐 This is a static property.

◆ ESLint.fromOptionsModule(optionsURL)

const eslint = await ESLint.fromOptionsModule(optionsURL);

这个方法创建了一个 ESLint 类的实例,其选项从模块中加载,例如:

🌐 This method creates an instance of the ESLint class with options loaded from a module, for example:

// eslint-options.js

import config from "./my-eslint-config.js";

export default {
	concurrency: "auto",
	overrideConfig: config,
	overrideConfigFile: true,
	stats: true,
};
// main.js

...
const optionsURL = new URL("./eslint-options.js", import.meta.url);
const eslint = await ESLint.fromOptionsModule(optionsURL);
...

concurrency 选项要求所有其他选项都必须可克隆,以便它们可以传递给工作线程,但当选项是从模块加载时,这一限制不适用,因为在这种情况下,工作线程接收到的是模块的 URL 而不是选项对象。

🌐 The concurrency option requires all other options to be cloneable so that they can be passed to worker threads, but this restriction does not apply when options are loaded from a module, because in that case worker threads are passed the module URL instead of the options object.

这是一个静态方法。

🌐 This is a static method.

参数

🌐 Parameters

  • optionsURL (URL)
    选项模块的 URL。这可以是任何有效的 URL,例如文件 URL 或数据 URL。

返回值

🌐 Return Value

  • (Promise<ESLint>)
    ESLint 类的新实例。

◆ ESLint.outputFixes(results)

await ESLint.outputFixes(results);

此方法将 ESLint 自动修复功能修改的代码写入其各自的文件。如果任何被修改的文件不存在,此方法将不执行任何操作。

🌐 This method writes code modified by ESLint’s autofix feature into its respective file. If any of the modified files don’t exist, this method does nothing.

这是一个静态方法。

🌐 This is a static method.

参数

🌐 Parameters

  • results (LintResult[])
    要写入的 LintResult 对象。

返回值

🌐 Return Value

  • (Promise<void>)
    在所有文件写入完成后将被兑现的承诺。

◆ ESLint.getErrorResults(results)

const filteredResults = ESLint.getErrorResults(results);

此方法会复制给定的结果并移除警告。返回值仅包含错误。

🌐 This method copies the given results and removes warnings. The returned value contains only errors.

这是一个静态方法。

🌐 This is a static method.

参数

🌐 Parameters

  • results (LintResult[])
    要过滤的 LintResult 对象。

返回值

🌐 Return Value

  • (LintResult[])
    已过滤的 LintResult 对象。

◆ LintResult 类型

🌐 ◆ LintResult type

LintResult 值是每个文件的代码检查结果信息。eslint.lintFiles()eslint.lintText() 方法返回它。它具有以下属性:

🌐 The LintResult value is the information of the linting result of each file. The eslint.lintFiles() and eslint.lintText() methods return it. It has the following properties:

  • filePath (string)
    此结果文件的绝对路径。如果文件路径未知(当你没有向 eslint.lintText() 方法传递 options.filePath 选项时),则为字符串 "<text>"
  • messages (LintMessage[])
    LintMessage 对象的数组。
  • suppressedMessages (SuppressedLintMessage[])
    SuppressedLintMessage 对象的数组。
  • fixableErrorCount (number)
    可以通过 fix 构造函数选项自动修复的错误数量。
  • fixableWarningCount (number)
    可以通过 fix 构造函数选项自动修复的警告数量。
  • errorCount (number)
    错误数量。这包括可修复的错误和致命错误。
  • fatalErrorCount (number)
    致命错误的数量。
  • warningCount (number)
    警告数量。这包括可修复的警告。
  • output (string | undefined)
    修改后的源代码文本。如果没有任何可修复的信息,此属性未定义。
  • source (string | undefined)
    原始源代码文本。如果任何消息不存在或 output 属性存在,则此属性未定义。
  • stats (Stats | undefined)
    Stats 对象。它包含使用 stats 选项收集的 lint 性能统计信息。
  • usedDeprecatedRules ({ ruleId: string; replacedBy: string[]; info: DeprecatedInfo | undefined }[])
    关于用于检查此文件的已弃用规则的信息。如果规则使用了新的 deprecated 属性,则 info 属性设置为 rule.meta.deprecated

◆ LintMessage 类型

🌐 ◆ LintMessage type

LintMessage 值是每个代码检查错误的信息。LintResult 类型的 messages 属性包含它。它具有以下属性:

🌐 The LintMessage value is the information of each linting error. The messages property of the LintResult type contains it. It has the following properties:

  • ruleId (string | null)
    生成此 lint 消息的规则名称。如果此消息是由 ESLint 核心生成而不是规则生成的,则为 null
  • severity (1 | 2)
    此消息的严重性。1表示警告,2表示错误。
  • fatal (boolean | undefined)
    true 如果这是与规则无关的严重错误,例如解析错误。
  • message (string)
    错误信息。
  • messageId (string | undefined)
    lint 错误的消息 ID。如果规则不使用消息 ID,则此属性未定义。
  • line (number | undefined)
    此消息起始点的基于1的行号。
  • column (number | undefined)
    此消息起始点的基于1的列号。
  • endLine (number | undefined)
    此消息结束点的基于1的行号。如果此消息不是一个范围,则此属性未定义。
  • endColumn (number | undefined)
    此消息结束点的基于1的列号。如果此消息不是一个范围,则此属性未定义。
  • fix (EditInfo | undefined)
    autofix 的 EditInfo 对象。如果此消息无法修复,则此属性未定义。
  • suggestions ({ desc: string; fix: EditInfo; messageId?: string; data?: object }[] | undefined)
    建议列表。每个建议都是一个描述和一个用于修复代码的 EditInfo 对象的组合。像编辑器集成这样的 API 用户可以选择其中一个来修复此消息的问题。如果此消息没有任何建议,则此属性未定义。

◆ SuppressedLintMessage 类型

🌐 ◆ SuppressedLintMessage type

SuppressedLintMessage 值是每个被抑制的 linting 错误的信息。[LintResult] 类型的 suppressedMessages 属性包含它。它具有以下属性:

🌐 The SuppressedLintMessage value is the information of each suppressed linting error. The suppressedMessages property of the LintResult type contains it. It has the following properties:

  • ruleId (string | null)
    LintMessage 类型中的 ruleId 相同。
  • severity (1 | 2)
    LintMessage 类型中的 severity 相同。
  • fatal (boolean | undefined)
    LintMessage 类型中的 fatal 相同。
  • message (string)
    LintMessage 类型中的 message 相同。
  • messageId (string | undefined)
    LintMessage 类型中的 messageId 相同。
  • line (number | undefined)
    LintMessage 类型中的 line 相同。
  • column (number | undefined)
    LintMessage 类型中的 column 相同。
  • endLine (number | undefined)
    LintMessage 类型中的 endLine 相同。
  • endColumn (number | undefined)
    LintMessage 类型中的 endColumn 相同。
  • fix (EditInfo | undefined)
    LintMessage 类型中的 fix 相同。
  • suggestions ({ desc: string; fix: EditInfo; messageId?: string; data?: object }[] | undefined)
    LintMessage 类型中的 suggestions 相同。
  • suppressions ({ kind: string; justification: string}[])
    抑制列表。每个抑制都是一种类型和一个理由的组合。

◆ EditInfo 类型

🌐 ◆ EditInfo type

EditInfo 值是用于编辑文本的信息。LintMessage 类型的 fixsuggestions 属性包含它。它具有以下属性:

🌐 The EditInfo value is information to edit text. The fix and suggestions properties of LintMessage type contain it. It has following properties:

  • range ([number, number])
    要从源代码文本中删除的以 0 为起点的索引对。
  • text (string)
    要添加的文本。

此编辑信息意味着用 text 属性的值替换 range 属性的范围。这就像 sourceCodeText.slice(0, edit.range[0]) + edit.text + sourceCodeText.slice(edit.range[1])。因此,如果 range[0]range[1] 属性值相同,则是添加;如果 text 属性值为空字符串,则是移除。

🌐 This edit information means replacing the range of the range property by the text property value. It’s like sourceCodeText.slice(0, edit.range[0]) + edit.text + sourceCodeText.slice(edit.range[1]). Therefore, it’s an add if the range[0] and range[1] property values are the same value, and it’s removal if the text property value is empty string.

◆ LoadedFormatter 类型

🌐 ◆ LoadedFormatter type

LoadedFormatter 值是将 LintResult 对象转换为文本的对象。eslint.loadFormatter() 方法返回它。它具有以下方法:

🌐 The LoadedFormatter value is the object to convert the LintResult objects to text. The eslint.loadFormatter() method returns it. It has the following method:

  • format ((results: LintResult[], resultsMeta?: ResultsMeta) => string | Promise<string>)
    LintResult 对象转换为文本的方法。resultsMeta 是一个可选参数,主要用于 ESLint CLI,并且可以包含 colormaxWarningsExceeded 属性,当此方法调用底层格式化函数时,这些属性会通过 context 对象传递。请注意,ESLint 会自动生成 context 对象的 cwdrulesMeta 属性,因此在调用此方法时通常不需要传入第二个参数。

loadESLint()

loadESLint() 函数用于希望支持不同 ESLint 版本的集成。该函数根据提供的参数返回正确的 ESLint 类实现:

🌐 The loadESLint() function is used for integrations that wish to support different ESLint versions. This function returns the correct ESLint class implementation based on the arguments provided:

const { loadESLint } = require("eslint");

// loads the default ESLint that the CLI would use based on process.cwd()
const DefaultESLint = await loadESLint();

// loads the flat config version specifically
const FlatESLint = await loadESLint({ useFlatConfig: true });

// loads the legacy version specifically if possible, otherwise falls back to flat config version
const LegacyESLint = await loadESLint({ useFlatConfig: false });

然后你可以使用返回的构造函数来实例化一个新的 ESLint 实例,如下所示:

🌐 You can then use the returned constructor to instantiate a new ESLint instance, like this:

// loads the default ESLint that the CLI would use based on process.cwd()
const DefaultESLint = await loadESLint();
const eslint = new DefaultESLint();

如果你不确定返回的构造函数使用的是哪种配置系统,请检查 configType 属性,它要么是 "flat" 要么是 "eslintrc"

🌐 If you’re ever unsure which config system the returned constructor uses, check the configType property, which is either "flat" or "eslintrc":

// loads the default ESLint that the CLI would use based on process.cwd()
const DefaultESLint = await loadESLint();

if (DefaultESLint.configType === "flat") {
	// do something specific to flat config
}

如果你不需要同时支持旧的和新的配置系统,那么建议直接使用 ESLint 构造函数。

SourceCode

SourceCode 类型表示 ESLint 执行的已解析源代码。它在 ESLint 内部使用,同时也可用于已经解析的代码。你可以通过传入表示代码的文本字符串和 ESTree 格式的抽象语法树(AST)(包括位置信息、范围信息、注释和标记)来创建一个 SourceCode 的新实例:

🌐 The SourceCode type represents the parsed source code that ESLint executes on. It’s used internally in ESLint and is also available so that already-parsed code can be used. You can create a new instance of SourceCode by passing in the text string representing the code and an abstract syntax tree (AST) in ESTree format (including location information, range information, comments, and tokens):

const SourceCode = require("eslint").SourceCode;

const code = new SourceCode("var foo = bar;", ast);

SourceCode 构造函数如果 AST 缺少任何必需的信息,则会抛出错误。

🌐 The SourceCode constructor throws an error if the AST is missing any of the required information.

SourceCode 构造函数会去除 Unicode BOM。请注意,AST 也应该从已去除 BOM 的文本中解析。

🌐 The SourceCode constructor strips Unicode BOM. Please note the AST also should be parsed from stripped text.

const SourceCode = require("eslint").SourceCode;

const code = new SourceCode("\uFEFFvar foo = bar;", ast);

assert(code.hasBOM === true);
assert(code.text === "var foo = bar;");

SourceCode#splitLines()

这是 SourceCode 上的一个静态函数,用于将源代码文本拆分成一个行数组。

🌐 This is a static function on SourceCode that is used to split the source code text into an array of lines.

const SourceCode = require("eslint").SourceCode;

const code = "var a = 1;\nvar b = 2;";

// split code into an array
const codeLines = SourceCode.splitLines(code);

/*
    Value of codeLines will be
    [
        "var a = 1;",
        "var b = 2;"
    ]
 */

Linter

Linter 对象执行 JavaScript 代码的实际评估。它不进行任何文件系统操作,它只是解析代码并报告相关内容。特别是,Linter 对象不处理配置文件。除非你在浏览器中工作,否则你可能想使用 ESLint 类

🌐 The Linter object does the actual evaluation of the JavaScript code. It doesn’t do any filesystem operations, it simply parses and reports on the code. In particular, the Linter object does not process configuration files. Unless you are working in the browser, you probably want to use the ESLint class instead.

Linter 是一个构造函数,你可以通过传入你想使用的选项来创建一个新实例。可用的选项有:

🌐 The Linter is a constructor, and you can create a new instance by passing in the options you want to use. The available options are:

  • cwd - 应被视为当前工作目录的目录路径。它可以被来自 context.cwd 的规则访问(参见 上下文对象)。如果 cwdundefined,则在全局 process 对象被定义的情况下(例如,在 Node.js 运行时)它将被标准化为 process.cwd(),否则为 undefined

例如:

🌐 For example:

const Linter = require("eslint").Linter;
const linter1 = new Linter({ cwd: "path/to/project" });
const linter2 = new Linter();

在此示例中,运行在 linter1 上的规则将从 context.cwd 获取 path/to/project。 运行在 linter2 上的规则如果全局 process 对象已定义将获取 process.cwd(),否则将获取 undefined(例如在浏览器 https://eslint.nodejs.cn/demo 上)。

Linter#验证

🌐 Linter#verify

Linter 上最重要的方法是 verify(),它会启动对给定文本的 linting。该方法接受三个参数:

🌐 The most important method on Linter is verify(), which initiates linting of the given text. This method accepts three arguments:

  • code - 对源代码进行 lint(一个字符串或 SourceCode 的实例)。
  • config - 一个 [配置对象] 或一组配置对象。
  • options - (可选) 此次运行的附加选项。
    • filename - (可选)与源代码关联的文件名。
    • preprocess - (可选)一个函数,插件中的处理器 文档将其描述为 preprocess 方法。
    • postprocess - (可选)一个函数,插件中的处理器 文档将其描述为 postprocess 方法。
    • filterCodeBlock - (可选) 一个决定 linter 应采用哪些代码块的函数。该函数接收两个参数。第一个参数是代码块的虚拟文件名。第二个参数是代码块的文本。如果函数返回 true,则 linter 采用该代码块。如果省略该函数,linter 仅采用 *.js 代码块。如果你提供了一个 filterCodeBlock 函数,它会覆盖此默认行为,因此 linter 不会自动采用 *.js 代码块。
    • disableFixes - (可选)当设置为 true 时,linter 不会生成 lint 结果的 fixsuggestions 属性。
    • allowInlineConfig - (可选) 设置为 false 以禁止内联注释更改 ESLint 规则。
    • reportUnusedDisableDirectives - (可选) 当设置为 true 时,会在本来在禁用区域不会报告问题的情况下,为未使用的 eslint-disableeslint-enable 指令添加报告错误。
    • ruleFilter - (可选)一个函数谓词,用于决定哪些规则应该执行。它接收一个包含 ruleIdseverity 的对象,并返回 true 如果该规则应该执行。

如果第三个参数是字符串,它被解释为 filename

🌐 If the third argument is a string, it is interpreted as the filename.

你可以这样调用 verify()

🌐 You can call verify() like this:

const Linter = require("eslint").Linter;
const linter = new Linter();

const messages = linter.verify(
	"var foo;",
	{
		rules: {
			semi: 2,
		},
	},
	{ filename: "foo.js" },
);

// or using SourceCode

const Linter = require("eslint").Linter,
	linter = new Linter(),
	SourceCode = require("eslint").SourceCode;

const code = new SourceCode("var foo = bar;", ast);

const messages = linter.verify(
	code,
	{
		rules: {
			semi: 2,
		},
	},
	{ filename: "foo.js" },
);

verify() 方法返回一个包含有关 linting 警告和错误信息的对象数组。示例如下:

🌐 The verify() method returns an array of objects containing information about the linting warnings and errors. Here’s an example:

[
	{
		fatal: false,
		ruleId: "semi",
		severity: 2,
		line: 1,
		column: 23,
		message: "Expected a semicolon.",
		fix: {
			range: [1, 15],
			text: ";",
		},
	},
];

每条 linting 消息的可用信息是:

🌐 The information available for each linting message is:

  • column - 发生错误的列。
  • fatal - 通常省略,但如果存在解析错误(与规则无关),则将设置为 true。
  • line - 发生错误的行。
  • message - 应该输出的消息。
  • messageId - 用于生成消息的消息 ID(如果规则不使用消息 ID,则省略此属性)。
  • ruleId - 触发消息的规则的 ID(如果 fatal 为真,则为 null)。
  • severity - 1 或 2,具体取决于你的配置。
  • endColumn - 发生错误的范围的结束列(如果不是范围,则省略此属性)。
  • endLine - 发生错误的范围的结束行(如果不是范围,则省略此属性)。
  • fix - 描述问题修复的对象(如果没有修复可用,则省略此属性)。
  • suggestions - 一个描述可能的 lint 修复的对象数组,供编辑器以编程方式启用(详见 使用规则文档)。

你可以通过 getSuppressedMessages() 方法获取上一次运行中被抑制的消息。如果没有上一次运行,getSuppressedMessage() 将返回一个空列表。

🌐 You can get the suppressed messages from the previous run by getSuppressedMessages() method. If there is not a previous run, getSuppressedMessage() will return an empty list.

const Linter = require("eslint").Linter;
const linter = new Linter();

const messages = linter.verify(
	"var foo = bar; // eslint-disable-line -- Need to suppress",
	{
		rules: {
			semi: ["error", "never"],
		},
	},
	{ filename: "foo.js" },
);
const suppressedMessages = linter.getSuppressedMessages();

console.log(suppressedMessages[0].suppressions); // [{ "kind": "directive", "justification": "Need to suppress" }]

你也可以通过使用 getSourceCode() 方法获取在 linter 内部使用的 SourceCode 对象的实例:

🌐 You can also get an instance of the SourceCode object used inside of linter by using the getSourceCode() method:

const Linter = require("eslint").Linter;
const linter = new Linter();

const messages = linter.verify(
	"var foo = bar;",
	{
		rules: {
			semi: 2,
		},
	},
	{ filename: "foo.js" },
);

const code = linter.getSourceCode();

console.log(code.text); // "var foo = bar;"

通过这种方式,你可以检索上一次运行 linter.verify() 时使用的文本和 AST。

🌐 In this way, you can retrieve the text and AST used for the last run of linter.verify().

Linter#verifyAndFix()

这种方法类似于 verify,但它还会运行自动修复逻辑,类似于命令行上的 --fix 标志。结果对象将包含自动修复后的代码,以及未被自动修复的代码的任何剩余 lint 消息。

🌐 This method is similar to verify except that it also runs autofixing logic, similar to the --fix flag on the command line. The result object will contain the autofixed code, along with any remaining linting messages for the code that were not autofixed.

const Linter = require("eslint").Linter;
const linter = new Linter();

const messages = linter.verifyAndFix("var foo", {
	rules: {
		semi: 2,
	},
});

此方法的输出对象:

🌐 Output object from this method:

{
    fixed: true,
    output: "var foo;",
    messages: []
}

可用的信息是:

🌐 The information available is:

  • fixed - 是的,如果代码是固定的。
  • output - 固定代码文本(如果未应用任何修复,可能与输入相同)。
  • messages - 给定代码的所有消息集合(它包含与上面 verify 块中解释的相同信息)。

Linter#version/Linter.version

每个 Linter 实例都有一个 version 属性,其中包含 Linter 实例所属的 ESLint 的语义版本号。

🌐 Each instance of Linter has a version property containing the semantic version number of ESLint that the Linter instance is from.

const Linter = require("eslint").Linter;
const linter = new Linter();

linter.version; // => '9.0.0'

还有一个 Linter.version 属性,你可以在不实例化 Linter 的情况下读取它:

🌐 There is also a Linter.version property that you can read without instantiating Linter:

const Linter = require("eslint").Linter;

Linter.version; // => '9.0.0'

Linter#getTimes()

此方法用于获取处理(解析、修复、代码检查)文件所花费的时间。请参见 Stats 对象的 times 属性。

🌐 This method is used to get the times spent on (parsing, fixing, linting) a file. See times property of the Stats object.

Linter#getFixPassCount()

此方法用于获取自动修复执行的次数。请参阅 Stats 对象的 fixPasses 属性。

🌐 This method is used to get the number of autofix passes made. See fixPasses property of the Stats object.

Linter#hasFlag()

此方法用于确定是否设置了给定的功能标志,如以下示例所示:

🌐 This method is used to determine if a given feature flag is set, as in this example:

const Linter = require("eslint").Linter;
const linter = new Linter({ flags: ["x_feature"] });

console.log(linter.hasFlag("x_feature")); // true

RuleTester

eslint.RuleTester 是一个用于为 ESLint 规则编写测试的工具。它在内部用于随 ESLint 提供的打包规则,也可以被插件使用。

用法示例:

🌐 Example usage:

"use strict";

const rule = require("../../../lib/rules/my-rule"),
	RuleTester = require("eslint").RuleTester;

const ruleTester = new RuleTester();

ruleTester.run("my-rule", rule, {
	valid: [
		{
			code: "var foo = true",
			options: [{ allowFoo: true }],
		},
	],

	invalid: [
		{
			code: "var invalidVariable = true",
			errors: [{ message: "Unexpected invalid variable." }],
		},
		{
			code: "var invalidVariable = true",
			errors: [{ message: /^Unexpected.+variable/ }],
		},
	],

	// optional
	assertionOptions: {
		requireMessage: true,
		requireLocation: false,
		requireData: true,
	},
});

RuleTester 构造函数接受一个可选的对象参数,可用于为你的测试用例指定默认值。例如,如果你的所有测试用例都使用 ES2015,你可以将其设置为默认值:

🌐 The RuleTester constructor accepts an optional object argument, which can be used to specify defaults for your test cases. For example, if all of your test cases use ES2015, you can set it as a default:

const ruleTester = new RuleTester({ languageOptions: { ecmaVersion: 2015 } });

RuleTester.setDefaultConfig(config)

const RuleTester = require("eslint").RuleTester;

// Apply a default config for subsequently created RuleTester instances
RuleTester.setDefaultConfig({
	languageOptions: { ecmaVersion: 2022, sourceType: "module" },
});

const ruleTester = new RuleTester(); // picks up defaults above

设置此调用后创建的 RuleTester 实例使用的默认配置。

🌐 Sets the default configuration used by RuleTester instances created after this call.

这是一个静态方法。

🌐 This is a static method.

参数

🌐 Parameters

  • config (Config)
    一个默认应用于所有测试的[配置对象]。它在每个实例的RuleTester构造函数选项和每个测试配置之前应用。如果config不是对象,则会抛出TypeError

RuleTester.getDefaultConfig()

const currentDefaultConfig = RuleTester.getDefaultConfig();

返回 RuleTester 当前使用的默认配置。

🌐 Returns the current default configuration used by RuleTester.

这是一个静态方法。

🌐 This is a static method.

返回值

🌐 Return Value

  • (Config)
    当前的默认配置对象。

RuleTester.resetDefaultConfig()

RuleTester.resetDefaultConfig();

将默认配置重置回 ESLint 内置的默认设置,用于随后创建的 RuleTester 实例。

🌐 Resets the default configuration back to ESLint’s built-in defaults for subsequently created RuleTester instances.

这是一个静态方法。

🌐 This is a static method.

RuleTester#run()

RuleTester#run() 方法用于运行测试。它应传递以下参数:

🌐 The RuleTester#run() method is used to run the tests. It should be passed the following arguments:

  • 规则的名称(字符串)。
  • 规则对象本身(见 “使用规则”)。
  • 一个包含 validinvalid 属性的对象,每个属性都是一个包含测试用例的数组。
    • 在这个对象中,你还可以传递 assertionOptions 属性来配置对 invalid 测试用例断言的要求,以强制一致性。

测试用例是具有以下属性的对象:

🌐 A test case is an object with the following properties:

  • name(字符串,可选):用于测试用例的名称,以便更容易找到。
  • code(字符串,必需):规则应运行的源代码。
  • options(数组,可选):传递给规则的选项。规则的严重性不应包含在此列表中。
  • before(函数,可选):在测试用例之前执行的函数。
  • after(函数,可选):在测试用例完成后无论结果如何都要执行的函数。
  • filename(字符串,可选):给定案例的文件名(对于对文件名进行断言的规则非常有用)。
  • only(布尔值,可选):仅在受支持的测试框架中为调试运行此用例。

除了上述属性外,无效测试用例还可以具有以下属性:

🌐 In addition to the properties above, invalid test cases can also have the following properties:

  • errors(数字或数组,必填):断言规则在此代码上运行时预期产生的错误的一些属性。如果这是一个数字,则断言产生的错误数量。否则,这应该是一个对象列表,每个对象包含关于单个报告错误的信息。错误可以使用以下属性(除非另有说明,否则均为可选项):

    • message (字符串/正则表达式):错误信息。必须提供此项或 messageId
    • messageId(字符串):错误的 ID。必须提供此项或 message。有关详细信息,请参见 使用 messageId 测试错误
    • data(对象):占位数据,可与 messageId 结合使用。
    • line(数字):报告位置的以1为起始的行号。
    • column(数字):报告位置的以1为起始的列号。
    • endLine(数字):报告位置结束的基于1的行号。
    • endColumn(数字):报告位置结束的基于1的列号。
    • suggestions(数组):包含要检查的建议详情的对象数组。如果规则生成建议,则必需。详情请参见测试建议

    如果提供了一个字符串作为错误而不是对象,则该字符串用于断言错误的 message

  • output(字符串,如果规则修复代码则为必填):断言在使用此规则进行单次自动修复(例如使用 --fix 命令行标志)时将生成的输出。如果此值为 null 或省略,则断言没有报告的问题建议进行自动修复。

测试用例的任何附加属性将直接作为配置选项传递给代码检查工具。例如,测试用例可以有一个 languageOptions 属性来配置解析器行为:

🌐 Any additional properties of a test case will be passed directly to the linter as config options. For example, a test case can have a languageOptions property to configure parser behavior:

{
    code: "let foo;",
    languageOptions: { ecmaVersion: 2015 }
}

如果一个有效的测试用例只使用 code 属性,它可以选择作为包含代码的字符串提供,而不是带有 code 键的对象。

🌐 If a valid test case only uses the code property, it can optionally be provided as a string containing the code, rather than an object with a code key.

你可以选择性地配置以下适用于该调用中所有错误断言的 assertionOptions

🌐 You can optionally configure the following assertionOptions that apply to all error assertions in that call:

  • requireMessage(布尔值/"message"/"messageId",可选):
    • 如果 true,每个 errors 块必须检查预期的错误消息,可以通过 errors 数组中的字符串/正则表达式值,或者通过错误对象中的 message/messageId 来进行。
    • 如果 "message",每个 errors 块必须检查预期的错误消息,可以通过 errors 数组中的字符串/正则表达式值,或者通过错误对象中的 message 来实现。
    • 如果 "messageId",每个 errors 块必须通过错误对象中的 messageId 检查预期的错误消息。
  • requireLocation(布尔值,可选):如果 true,每个 errors 块必须是对象数组,并且每个对象必须包含位置属性 linecolumnendLineendColumn。如果实际错误中不包含 endLineendColumn,这些属性可以省略。
  • requireData(布尔值/"error"/"suggestion",可选):
    • 如果 true,每个指定了 messageId 的错误对象和每个指定了 messageId 的建议对象如果由 messageId 引用的消息有 占位符,也必须指定 data
    • 如果 "error",每个指定了 messageId 的错误对象也必须指定 data,如果 messageId 引用的消息有 占位符
    • 如果 "suggestion",每个指定了 messageId 的建议对象在 messageId 引用的消息包含占位符的情况下,也必须指定 data

使用 messageId 测试错误

🌐 Testing Errors with messageId

如果正在测试的规则使用 messageId,你可以在测试用例中使用 messageId 属性来断言报告的错误的 messageId,而不是它的 message

🌐 If the rule under test uses messageIds, you can use messageId property in a test case to assert reported error’s messageId instead of its message.

{
    code: "let foo;",
    errors: [{ messageId: "unexpected" }]
}

对于带有占位符的消息,测试用例也可以使用 data 属性来额外断言报告的错误的 message

🌐 For messages with placeholders, a test case can also use data property to additionally assert reported error’s message.

{
    code: "let foo;",
    errors: [{ messageId: "unexpected", data: { name: "foo" } }]
}

请注意,测试用例中的 data 并不断言传递给 context.reportdata。相反,它用于形成预期的消息文本,然后与接收到的 message 进行比较。

🌐 Please note that data in a test case does not assert data passed to context.report. Instead, it is used to form the expected message text which is then compared with the received message.

测试修复

🌐 Testing Fixes

可以通过使用无效测试用例的 output 属性来测试应用修复的结果。只有当你预计某个修复将应用于指定的 code 时,才应使用 output 属性;如果代码不预期有任何更改,则可以安全地省略 output。下面是一个示例:

🌐 The result of applying fixes can be tested by using the output property of an invalid test case. The output property should be used only when you expect a fix to be applied to the specified code; you can safely omit output if no changes are expected to the code. Here’s an example:

ruleTester.run("my-rule-for-no-foo", rule, {
	valid: [],
	invalid: [
		{
			code: "var foo;",
			output: "var bar;",
			errors: [
				{
					messageId: "shouldBeBar",
					line: 1,
					column: 5,
				},
			],
		},
	],
});

在此无效测试用例结束时,RuleTester 期望应用一个修复,使代码从 var foo; 变为 var bar;。如果应用修复后的输出不匹配,则测试失败。

🌐 At the end of this invalid test case, RuleTester expects a fix to be applied that results in the code changing from var foo; to var bar;. If the output after applying the fix doesn’t match, then the test fails.

测试建议

🌐 Testing Suggestions

可以通过在错误对象上定义一个 suggestions 键来测试建议。如果这是一个数字,它将断言为错误提供的建议数量。否则,这应该是一个对象数组,每个对象包含关于单个提供建议的信息。可以使用以下属性:

🌐 Suggestions can be tested by defining a suggestions key on an errors object. If this is a number, it asserts the number of suggestions provided for the error. Otherwise, this should be an array of objects, each containing information about a single provided suggestion. The following properties can be used:

  • desc (字符串):建议的 desc 值。必须提供此项或 messageId
  • messageId (字符串):对于使用 messageId 的建议,提供的建议 messageId 值。必须提供此项或 desc
  • data(对象):占位数据,可与 messageId 结合使用。
  • output(字符串,必填):表示将建议修复应用于输入代码后结果的代码字符串。

示例:

🌐 Example:

ruleTester.run("my-rule-for-no-foo", rule, {
	valid: [],
	invalid: [
		{
			code: "var foo;",
			errors: [
				{
					suggestions: [
						{
							desc: "Rename identifier 'foo' to 'bar'",
							output: "var bar;",
						},
					],
				},
			],
		},
	],
});

建议测试对象中的messageIddata属性的工作方式与错误测试对象中的相同。详细信息请参见使用messageId测试错误

ruleTester.run("my-rule-for-no-foo", rule, {
	valid: [],
	invalid: [
		{
			code: "var foo;",
			errors: [
				{
					suggestions: [
						{
							messageId: "renameFoo",
							data: { newName: "bar" },
							output: "var bar;",
						},
					],
				},
			],
		},
	],
});

自定义 RuleTester

🌐 Customizing RuleTester

RuleTester 依赖两个函数来运行测试:describeit。这些函数可以来自不同的来源:

  1. 如果 RuleTester.describeRuleTester.it 已经被设置为函数值,RuleTester 将使用 RuleTester.describeRuleTester.it 来运行测试。你可以使用此方法来自定义 RuleTester 的行为,以匹配你正在使用的测试框架。

    如果 RuleTester.itOnly 已被设置为一个函数值,RuleTester 将调用 RuleTester.itOnly 而不是 RuleTester.it 来运行带有 only: true 的用例。如果 RuleTester.itOnly 未设置但 RuleTester.it 拥有一个 only 函数属性,RuleTester 将回退到 RuleTester.it.only

  2. 否则,如果 describeit 作为全局存在,RuleTester 将使用 globalThis.describeglobalThis.it 来运行测试,并使用 globalThis.it.only 配合 only: true 来运行用例。这允许 RuleTester 在使用像 Mocha 这样的框架时无需任何额外配置就能工作。

  3. 否则,RuleTester#run 将会按照顺序执行所有测试,如果其中一个测试失败,它将抛出错误。这意味着你可以直接使用 Node.js 执行一个调用 RuleTester.run 的测试文件,而无需使用测试框架。

RuleTester#run 使用两个参数调用 describe 函数:一个描述规则的字符串,以及一个回调函数。该回调调用 it 函数,带有描述测试用例的字符串和一个测试函数。如果测试通过,测试函数将成功返回;如果测试失败,将抛出错误。only 的签名与 it 相同。RuleTester 会对每个用例调用 itonly,即使有些用例有 only: true,而测试框架负责实现测试用例的排他性。(注意,这在使用像 Mocha 这样的框架时是测试套件的标准行为;只有在你计划自定义 RuleTester.describeRuleTester.itRuleTester.itOnly 时,这条信息才相关。)

RuleTester 自定义示例:

🌐 Example of customizing RuleTester:

"use strict";

const RuleTester = require("eslint").RuleTester,
	test = require("my-test-runner"),
	myRule = require("../../../lib/rules/my-rule");

RuleTester.describe = function (text, method) {
	RuleTester.it.title = text;
	return method.call(this);
};

RuleTester.it = function (text, method) {
	test(RuleTester.it.title + ": " + text, method);
};

// then use RuleTester as documented

const ruleTester = new RuleTester();

ruleTester.run("my-rule", myRule, {
	valid: [
		// valid test cases
	],
	invalid: [
		// invalid test cases
	],
});