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 的未记录部分需要你自担风险。只有本文档中特别提到的那些部件才被批准使用,并且将保持稳定和可靠。任何未记录的内容都是不稳定的,可能随时更改或删除。

¥Note: Use undocumented parts of the API at your own risk. Only those parts that are specifically mentioned in this document are approved for use and will remain stable and reliable. Anything left undocumented is unstable and may change or be removed at any point.

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.cwd (string)
    Default is process.cwd(). The working directory. This must be an absolute path.

  • options.errorOnUnmatchedPattern (boolean)
    默认为 true。除非设置为 false,否则 eslint.lintFiles() 方法会在找不到目标文件时抛出错误。

    ¥options.errorOnUnmatchedPattern (boolean)
    Default is true. Unless set to false, the eslint.lintFiles() method will throw an error when no target files are found.

  • options.globInputPaths (boolean)
    默认为 true。如果存在 false,则 eslint.lintFiles() 方法不解释通配符模式。

    ¥options.globInputPaths (boolean)
    Default is true. If false is present, the eslint.lintFiles() method doesn’t interpret glob patterns.

  • options.ignore (boolean)
    默认为 true。如果存在 false,则 eslint.lintFiles() 方法不考虑配置中的 ignorePatterns

    ¥options.ignore (boolean)
    Default is true. If false is present, the eslint.lintFiles() method doesn’t respect ignorePatterns in your configuration.

  • options.ignorePatterns (string[] | null)
    默认为 null。除了配置忽略之外,还要使用忽略文件模式。这些模式与 cwd 相关。

    ¥options.ignorePatterns (string[] | null)
    Default is null. Ignore file patterns to use in addition to config ignores. These patterns are relative to cwd.

  • options.passOnNoPatterns (boolean)
    默认为 false。当设置为 true 时,丢失模式会导致 linting 操作短路并且不报告任何故障。

    ¥options.passOnNoPatterns (boolean)
    Default is false. When set to true, missing patterns cause the linting operation to short circuit and not report any failures.

  • options.warnIgnored (boolean)
    默认为 true。当文件列表包含被忽略的文件时显示警告。

    ¥options.warnIgnored (boolean)
    Default is true. Show warnings when the file list includes ignored files.

代码检查

¥Linting

  • options.allowInlineConfig (boolean)
    默认为 true。如果存在 false,ESLint 会抑制源代码中的指令注释。如果此选项为 false,它将覆盖你配置中的 noInlineConfig 设置。

    ¥options.allowInlineConfig (boolean)
    Default is true. If false is present, ESLint suppresses directive comments in source code. If this option is false, it overrides the noInlineConfig setting in your configurations.

  • options.baseConfig (ConfigData | null)
    默认为 null配置对象,由与此实例一起使用的所有配置扩展。如果你的配置文件没有配置它,你可以使用此选项来定义将使用的默认设置。

    ¥options.baseConfig (ConfigData | null)
    Default is null. Configuration object, extended by all configurations used with this instance. You can use this option to define the default settings that will be used if your configuration files don’t configure it.

  • options.overrideConfig (ConfigData | null)
    默认为 null配置对象,覆盖与此实例一起使用的所有配置。你可以使用此选项来定义将使用的设置,即使你的配置文件配置了它。

    ¥options.overrideConfig (ConfigData | null)
    Default is null. Configuration object, overrides all configurations used with this instance. You can use this option to define the settings that will be used even if your configuration files configure it.

  • options.overrideConfigFile (string | boolean)
    默认为 false。配置文件的路径会覆盖与此实例一起使用的所有配置。应用此选项后应用 options.overrideConfig 选项。

    ¥options.overrideConfigFile (string | boolean)
    Default is false. The path to a configuration file, overrides all configurations used with this instance. The options.overrideConfig option is applied after this option is applied.

  • options.plugins (Record<string, Plugin> | null)
    默认为 null。ESLint 用于配置的 plugins 设置的插件实现。这是一个类似映射的对象。这些键是插件 ID,每个值都是实现。

    ¥options.plugins (Record<string, Plugin> | null)
    Default is null. The plugin implementations that ESLint uses for the plugins setting of your configuration. This is a map-like object. Those keys are plugin IDs and each value is implementation.

  • options.ruleFilter (({ruleId: string, severity: number}) => boolean)
    默认为 () => true。过滤要运行的规则的谓词函数。使用包含 ruleIdseverity 的对象调用此函数,如果应运行规则,则返回 true

    ¥options.ruleFilter (({ruleId: string, severity: number}) => boolean)
    Default is () => true. A predicate function that filters rules to be run. This function is called with an object containing ruleId and severity, and returns true if the rule should be run.

  • options.stats (boolean)
    默认为 false。当设置为 true 时,额外的统计信息将添加到 lint 结果中(请参阅 统计类型)。

    ¥options.stats (boolean)
    Default is false. When set to true, additional statistics are added to the lint results (see Stats type).

自动修复

¥Autofix

  • options.fix (boolean | (message: LintMessage) => boolean)
    默认为 false。如果存在 true,则 eslint.lintFiles()eslint.lintText() 方法在自动修复模式下工作。如果存在谓词函数,则这些方法将每个 lint 消息传递给该函数,然后仅使用该函数返回 true 的 lint 消息。

    ¥options.fix (boolean | (message: LintMessage) => boolean)
    Default is false. If true is present, the eslint.lintFiles() and eslint.lintText() methods work in autofix mode. If a predicate function is present, the methods pass each lint message to the function, then use only the lint messages for which the function returned true.

  • options.fixTypes (("directive" | "problem" | "suggestion" | "layout")[] | null)
    默认为 nulleslint.lintFiles()eslint.lintText() 方法用于自动修复的规则类型。

    ¥options.fixTypes (("directive" | "problem" | "suggestion" | "layout")[] | null)
    Default is null. The types of the rules that the eslint.lintFiles() and eslint.lintText() methods use for autofix.

缓存相关

¥Cache-related

  • options.cache (boolean)
    默认为 false。如果存在 true,则 eslint.lintFiles() 方法会缓存 lint 结果并在每个目标文件未更改时使用它。请注意,当你升级 ESLint 插件时,ESLint 不会清除缓存。在这种情况下,你必须手动删除缓存文件。即使你将 options.filePath 传递给该方法,eslint.lintText() 方法也不会使用缓存。

    ¥options.cache (boolean)
    Default is false. If true is present, the eslint.lintFiles() method caches lint results and uses it if each target file is not changed. Please mind that ESLint doesn’t clear the cache when you upgrade ESLint plugins. In that case, you have to remove the cache file manually. The eslint.lintText() method doesn’t use caches even if you pass the options.filePath to the method.

  • options.cacheLocation (string)
    默认为 .eslintcacheeslint.lintFiles() 方法将缓存写入此文件。

    ¥options.cacheLocation (string)
    Default is .eslintcache. The eslint.lintFiles() method writes caches into this file.

  • options.cacheStrategy (string)
    默认为 "metadata"。用于检测更改文件的缓存策略。可以是 "metadata""content"

    ¥options.cacheStrategy (string)
    Default is "metadata". Strategy for the cache to use for detecting changed files. Can be either "metadata" or "content".

◆ 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 目标文件。这可以包含任何文件路径、目录路径和通配符模式。

    ¥patterns (string | string[])
    The lint target files. This can contain any of file paths, directory paths, and glob patterns.

返回值

¥Return Value

  • (Promise<LintResult[]>)
    将通过 LintResult 对象数组实现的 promise。

    ¥(Promise<LintResult[]>)
    The promise that will be fulfilled with an array of LintResult objects.

◆ 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)
    要检查的源代码文本。

    ¥code (string)
    The source code text to check.

  • options.filePath (string)
    可选。源代码文本文件的路径。如果省略,则 result.filePath 变为字符串 "<text>"

    ¥options.filePath (string)
    Optional. The path to the file of the source code text. If omitted, the result.filePath becomes the string "<text>".

  • options.warnIgnored (boolean)
    可选,默认为传递给构造函数的 options.warnIgnored。如果 true 存在并且 options.filePath 是 ESLint 应该忽略的文件,则此方法返回包含警告消息的 lint 结果。

    ¥options.warnIgnored (boolean)
    Optional, defaults to options.warnIgnored passed to the constructor. If true is present and the options.filePath is a file ESLint should ignore, this method returns a lint result contains a warning message.

返回值

¥Return Value

  • (Promise<LintResult[]>)
    将通过 LintResult 对象数组实现的 promise。这是一个数组(尽管只有一个 lint 结果)以保持此方法与 eslint.lintFiles() 方法之间的接口相似。

    ¥(Promise<LintResult[]>)
    The promise that will be fulfilled with an array of LintResult objects. This is an array (despite there being only one lint result) in order to keep the interfaces between this and the eslint.lintFiles() method similar.

◆ 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 对象数组。

    ¥results (LintResult[])
    An array of LintResult objects returned from a call to ESLint#lintFiles() or ESLint#lintText().

返回值

¥Return Value

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

    ¥(Object)
    An object whose property names are the rule IDs from the results and whose property values are the rule’s meta information (if available).

◆ 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 设置。

    ¥filePath (string)
    The path to the file whose configuration you would like to calculate. Directory paths are forbidden because ESLint cannot handle the overrides setting.

返回值

¥Return Value

  • (Promise<Object>)
    将通过配置对象实现的 promise。

    ¥(Promise<Object>)
    The promise that will be fulfilled with a configuration object.

◆ eslint.isPathIgnored(filePath)

const isPathIgnored = await eslint.isPathIgnored(filePath);

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

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

参数

¥Parameters

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

    ¥filePath (string)
    The path to the file you want to check.

返回值

¥Return Value

  • (Promise<boolean>)
    无论文件是否被忽略,都将履行的 promise。如果文件被忽略,那么它将返回 true

    ¥(Promise<boolean>)
    The promise that will be fulfilled with whether the file is ignored or not. If the file is ignored, then it will return 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)
    要检查的文件的路径。允许以下值:

    ¥nameOrPath (string | undefined)
    The path to the file you want to check. The following values are allowed:

    • undefined。在这种情况下,加载 "stylish" 内置格式化程序。

      ¥undefined. In this case, loads the "stylish" built-in formatter.

    • 内置格式化器 的名称。

      ¥A name of built-in formatters.

    • 第三方格式化程序 的名称。举些例子:

      ¥A name of third-party formatters. For examples:

      • "foo" 将加载 eslint-formatter-foo

        ¥"foo" will load eslint-formatter-foo.

      • "@foo" 将加载 @foo/eslint-formatter

        ¥"@foo" will load @foo/eslint-formatter.

      • "@foo/bar" 将加载 @foo/eslint-formatter-bar

        ¥"@foo/bar" will load @foo/eslint-formatter-bar.

    • 定义格式化程序的文件的路径。路径必须包含一个或多个路径分隔符 (/),以便区分它是否是路径。例如,从 ./ 开始。

      ¥A path to the file that defines a formatter. The path must contain one or more path separators (/) in order to distinguish if it’s a path or not. For example, start with ./.

返回值

¥Return Value

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

    ¥(Promise<LoadedFormatter>)
    The promise that will be fulfilled with a LoadedFormatter object.

◆ 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.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 对象。

    ¥results (LintResult[])
    The LintResult objects to write.

返回值

¥Return Value

  • (Promise<void>)
    所有文件写入后将兑现的 promise。

    ¥(Promise<void>)
    The promise that will be fulfilled after all files are written.

◆ 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 个对象。

    ¥results (LintResult[])
    The LintResult objects to filter.

返回值

¥Return Value

  • (LintResult[])
    过滤了 LintResult 个对象。

    ¥(LintResult[])
    The filtered LintResult objects.

◆ LintResult 类型

¥◆ LintResult type

LintResult 值是每个文件的 linting 结果信息。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)
    此结果的文件的绝对路径。如果文件路径未知(当你没有将 options.filePath 选项传递给 eslint.lintText() 方法时),则这是字符串 "<text>"

    ¥filePath (string)
    The absolute path to the file of this result. This is the string "<text>" if the file path is unknown (when you didn’t pass the options.filePath option to the eslint.lintText() method).

  • messages (LintMessage[])
    LintMessage 对象的数组。

    ¥messages (LintMessage[])
    The array of LintMessage objects.

  • suppressedMessages (SuppressedLintMessage[])
    SuppressedLintMessage 对象的数组。

    ¥suppressedMessages (SuppressedLintMessage[])
    The array of SuppressedLintMessage objects.

  • fixableErrorCount (number)
    可以通过 fix 构造函数选项自动修复的错误数。

    ¥fixableErrorCount (number)
    The number of errors that can be fixed automatically by the fix constructor option.

  • fixableWarningCount (number)
    可以通过 fix 构造函数选项自动修复的警告数量。

    ¥fixableWarningCount (number)
    The number of warnings that can be fixed automatically by the fix constructor option.

  • errorCount (number)
    错误数。这包括可修复的错误和致命错误。

    ¥errorCount (number)
    The number of errors. This includes fixable errors and fatal errors.

  • fatalErrorCount (number)
    致命错误数。

    ¥fatalErrorCount (number)
    The number of fatal errors.

  • warningCount (number)
    警告数量。这包括可修复的警告。

    ¥warningCount (number)
    The number of warnings. This includes fixable warnings.

  • output (string | undefined)
    修改后的源代码文本。如果不存在任何可修复消息,则此属性未定义。

    ¥output (string | undefined)
    The modified source code text. This property is undefined if any fixable messages didn’t exist.

  • source (string | undefined)
    原始源代码文本。如果任何消息不存在或 output 属性存在,则此属性未定义。

    ¥source (string | undefined)
    The original source code text. This property is undefined if any messages didn’t exist or the output property exists.

  • stats (Stats | undefined)
    统计数据 对象。这包含使用 stats 选项收集的 lint 性能统计信息。

    ¥stats (Stats | undefined)
    The Stats object. This contains the lint performance statistics collected with the stats option.

  • usedDeprecatedRules ({ ruleId: string; replacedBy: string[] }[])
    有关用于检查此文件的已弃用规则的信息。

    ¥usedDeprecatedRules ({ ruleId: string; replacedBy: string[] }[])
    The information about the deprecated rules that were used to check this file.

◆ LintMessage 类型

¥◆ LintMessage type

LintMessage 值是每个 linting 错误的信息。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

    ¥ruleId (string | null)
    The rule name that generates this lint message. If this message is generated by the ESLint core rather than rules, this is null.

  • severity (1 | 2)
    此消息的严重性。1 表示警告,2 表示错误。

    ¥severity (1 | 2)
    The severity of this message. 1 means warning and 2 means error.

  • fatal (boolean | undefined)
    true 如果这是与规则无关的致命错误,例如解析错误。

    ¥fatal (boolean | undefined)
    true if this is a fatal error unrelated to a rule, like a parsing error.

  • message (string)
    错误消息。

    ¥message (string)
    The error message.

  • line (number | undefined)
    该消息的起始点的从 1 开始的行号。

    ¥line (number | undefined)
    The 1-based line number of the begin point of this message.

  • column (number | undefined)
    此消息的起始点的从 1 开始的列号。

    ¥column (number | undefined)
    The 1-based column number of the begin point of this message.

  • endLine (number | undefined)
    该消息结束点的从 1 开始的行号。如果此消息不是范围,则此属性未定义。

    ¥endLine (number | undefined)
    The 1-based line number of the end point of this message. This property is undefined if this message is not a range.

  • endColumn (number | undefined)
    此消息结束点的从 1 开始的列号。如果此消息不是范围,则此属性未定义。

    ¥endColumn (number | undefined)
    The 1-based column number of the end point of this message. This property is undefined if this message is not a range.

  • fix (EditInfo | undefined)
    autofix 的 EditInfo 对象。如果此消息不可修复,则此属性未定义。

    ¥fix (EditInfo | undefined)
    The EditInfo object of autofix. This property is undefined if this message is not fixable.

  • suggestions ({ desc: string; fix: EditInfo }[] | undefined)
    建议列表。每个建议都是一对描述和一个用于修复代码的 EditInfo 对象。编辑器集成等 API 用户可以选择其中之一来修复此消息的问题。如果此消息没有任何建议,则此属性未定义。

    ¥suggestions ({ desc: string; fix: EditInfo }[] | undefined)
    The list of suggestions. Each suggestion is the pair of a description and an EditInfo object to fix code. API users such as editor integrations can choose one of them to fix the problem of this message. This property is undefined if this message doesn’t have any suggestions.

◆ 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 相同。

    ¥ruleId (string | null)
    Same as ruleId in LintMessage type.

  • severity (1 | 2)
    LintMessage 型中的 severity 相同。

    ¥severity (1 | 2)
    Same as severity in LintMessage type.

  • fatal (boolean | undefined)
    LintMessage 型中的 fatal 相同。

    ¥fatal (boolean | undefined)
    Same as fatal in LintMessage type.

  • message (string)
    LintMessage 型中的 message 相同。

    ¥message (string)
    Same as message in LintMessage type.

  • line (number | undefined)
    LintMessage 型中的 line 相同。

    ¥line (number | undefined)
    Same as line in LintMessage type.

  • column (number | undefined)
    LintMessage 型中的 column 相同。

    ¥column (number | undefined)
    Same as column in LintMessage type.

  • endLine (number | undefined)
    LintMessage 型中的 endLine 相同。

    ¥endLine (number | undefined)
    Same as endLine in LintMessage type.

  • endColumn (number | undefined)
    LintMessage 型中的 endColumn 相同。

    ¥endColumn (number | undefined)
    Same as endColumn in LintMessage type.

  • fix (EditInfo | undefined)
    LintMessage 型中的 fix 相同。

    ¥fix (EditInfo | undefined)
    Same as fix in LintMessage type.

  • suggestions ({ desc: string; fix: EditInfo }[] | undefined)
    LintMessage 型中的 suggestions 相同。

    ¥suggestions ({ desc: string; fix: EditInfo }[] | undefined)
    Same as suggestions in LintMessage type.

  • suppressions ({ kind: string; justification: string}[])
    抑制列表。每一次压制都是一种类型和一种理由。

    ¥suppressions ({ kind: string; justification: string}[])
    The list of suppressions. Each suppression is the pair of a kind and a justification.

◆ 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 开始的索引。

    ¥range ([number, number])
    The pair of 0-based indices in source code text to remove.

  • text (string)
    要添加的文本。

    ¥text (string)
    The text to add.

该编辑信息表示用 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 是一个对象,如果设置了 --max-warnings 并且警告数超过限制,它将包含一个 maxWarningsExceeded 对象。maxWarningsExceeded 对象将包含两个属性:maxWarnings--max-warnings 选项的值,foundWarnings,lint 警告的数量。

    ¥format ((results: LintResult[], resultsMeta: ResultsMeta) => string | Promise<string>)
    The method to convert the LintResult objects to text. resultsMeta is an object that will contain a maxWarningsExceeded object if --max-warnings was set and the number of warnings exceeded the limit. The maxWarningsExceeded object will contain two properties: maxWarnings, the value of the --max-warnings option, and foundWarnings, the number of lint warnings.


loadESLint()

loadESLint() 函数用于希望支持当前配置系统(flat config)和旧配置系统(eslintrc)的集成。此函数根据提供的参数返回正确的 ESLint 类实现:

¥The loadESLint() function is used for integrations that wish to support both the current configuration system (flat config) and the old configuration system (eslintrc). 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 default ESLint that the CLI would use based on the provided cwd
const CwdDefaultESLint = await loadESLint({ cwd: "/foo/bar" });

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

// loads the legacy version specifically
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 构造函数。

¥If you don’t need to support both the old and new configuration systems, then it’s recommended to just use the ESLint constructor directly.


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);

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

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

SourceCode 构造函数剥离 Unicode BOM。请注意 AST 也应该从剥离的文本中解析出来。

¥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 中的规则或通过调用 context.getCwd()(请参阅 上下文对象)可以访问它。如果 cwdundefined,如果定义了全局 process 对象(例如,在 Node.js 运行时),它将被规范化为 process.cwd(),否则将规范化为 undefined

    ¥cwd - Path to a directory that should be considered as the current working directory. It is accessible to rules from context.cwd or by calling context.getCwd() (see The Context Object). If cwd is undefined, it will be normalized to process.cwd() if the global process object is defined (for example, in the Node.js runtime) , or undefined otherwise.

例如:

¥For example:

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

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

¥In this example, rules run on linter1 will get path/to/project from context.cwd or when calling context.getCwd(). Those run on linter2 will get process.cwd() if the global process object is defined or undefined otherwise (e.g. on the browser https://eslint.nodejs.cn/demo).

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 的字符串或实例)。

    ¥code - the source code to lint (a string or instance of SourceCode).

  • config - 配置对象 或配置对象数组。

    ¥config - a Configuration object or an array of configuration objects.

  • options - (可选)此运行的其他选项。

    ¥options - (optional) Additional options for this run.

    • filename - (可选)与源代码关联的文件名。

      ¥filename - (optional) the filename to associate with the source code.

    • preprocess - (可选)插件中的处理器 文档将其描述为 preprocess 方法的函数。

      ¥preprocess - (optional) A function that Processors in Plugins documentation describes as the preprocess method.

    • postprocess - (可选)插件中的处理器 文档将其描述为 postprocess 方法的函数。

      ¥postprocess - (optional) A function that Processors in Plugins documentation describes as the postprocess method.

    • filterCodeBlock - (可选)决定 linter 应采用哪些代码块的函数。该函数接收两个参数。第一个参数是代码块的虚拟文件名。第二个参数是代码块的文本。如果函数返回 true,则 linter 会采用代码块。如果省略该函数,则 linter 仅采用 *.js 代码块。如果你提供了 filterCodeBlock 函数,它会覆盖此默认行为,因此 linter 不会自动采用 *.js 代码块。

      ¥filterCodeBlock - (optional) A function that decides which code blocks the linter should adopt. The function receives two arguments. The first argument is the virtual filename of a code block. The second argument is the text of the code block. If the function returned true then the linter adopts the code block. If the function was omitted, the linter adopts only *.js code blocks. If you provided a filterCodeBlock function, it overrides this default behavior, so the linter doesn’t adopt *.js code blocks automatically.

    • disableFixes - (可选)当设置为 true 时,linter 不会生成 lint 结果的 fixsuggestions 属性。

      ¥disableFixes - (optional) when set to true, the linter doesn’t make either the fix or suggestions property of the lint result.

    • allowInlineConfig - (可选)设置为 false 以禁止内联注释更改 ESLint 规则。

      ¥allowInlineConfig - (optional) set to false to disable inline comments from changing ESLint rules.

    • reportUnusedDisableDirectives - (可选)当设置为 true 时,添加未使用的 eslint-disableeslint-enable 指令的报告错误,而无论如何在禁用区域中不会报告任何问题。

      ¥reportUnusedDisableDirectives - (optional) when set to true, adds reported errors for unused eslint-disable and eslint-enable directives when no problems would be reported in the disabled area anyway.

    • ruleFilter - (可选)决定应运行哪些规则的函数谓词。它接收包含 ruleIdseverity 的对象,如果应运行规则则返回 true

      ¥ruleFilter - (optional) A function predicate that decides which rules should run. It receives an object containing ruleId and severity, and returns true if the rule should be run.

如果第三个参数是一个字符串,它被解释为 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 - 发生错误的列。

    ¥column - the column on which the error occurred.

  • fatal - 通常省略,但如果存在解析错误(与规则无关),则将设置为 true。

    ¥fatal - usually omitted, but will be set to true if there’s a parsing error (not related to a rule).

  • line - 发生错误的行。

    ¥line - the line on which the error occurred.

  • message - 应该输出的消息。

    ¥message - the message that should be output.

  • nodeType - 与问题一起报告的节点或令牌类型。

    ¥nodeType - the node or token type that was reported with the problem.

  • ruleId - 触发消息的规则的 ID(如果 fatal 为真,则为 null)。

    ¥ruleId - the ID of the rule that triggered the messages (or null if fatal is true).

  • severity - 1 或 2,具体取决于你的配置。

    ¥severity - either 1 or 2, depending on your configuration.

  • endColumn - 发生错误的范围的结束列(如果不是范围,则省略此属性)。

    ¥endColumn - the end column of the range on which the error occurred (this property is omitted if it’s not range).

  • endLine - 发生错误的范围的结束行(如果不是范围,则省略此属性)。

    ¥endLine - the end line of the range on which the error occurred (this property is omitted if it’s not range).

  • fix - 描述问题修复的对象(如果没有修复可用,则省略此属性)。

    ¥fix - an object describing the fix for the problem (this property is omitted if no fix is available).

  • suggestions - 一个对象数组,描述了编辑器以编程方式启用的可能的 lint 修复(请参阅 使用规则文档 中的详细信息)。

    ¥suggestions - an array of objects describing possible lint fixes for editors to programmatically enable (see details in the Working with Rules docs).

你可以通过 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()

此方法类似于验证,只是它还运行自动修复逻辑,类似于命令行上的 --fix 标志。结果对象将包含自动修复的代码,以及未自动修复的代码的所有剩余 linting 消息。

¥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 - 是的,如果代码是固定的。

    ¥fixed - True, if the code was fixed.

  • output - 固定代码文本(如果未应用任何修复,可能与输入相同)。

    ¥output - Fixed code text (might be the same as input if no fixes were applied).

  • messages - 给定代码的所有消息的集合(它具有与上面在 verify 块下解释的相同的信息)。

    ¥messages - Collection of all messages for the given code (It has the same information as explained above under verify block).

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()

此方法用于获取(解析、修复、检查)文件所花费的时间。请参阅 统计数据 对象的 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()

此方法用于获取进行的自动修复遍数。请参阅 统计数据 对象的 fixPasses 属性。

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


RuleTester

eslint.RuleTester 是一个为 ESLint 规则编写测试的实用程序。它在内部用于 ESLint 附带的打包规则,也可以由插件使用。

¥eslint.RuleTester is a utility to write tests for ESLint rules. It is used internally for the bundled rules that come with ESLint, and it can also be used by plugins.

用法示例:

¥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/ }]
        }
    ]
});

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#run() 方法用于运行测试。它应该传递以下参数:

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

  • 规则的名称(字符串)

    ¥The name of the rule (string)

  • 规则对象本身(见 “使用规则”

    ¥The rule object itself (see “working with rules”)

  • 包含 validinvalid 属性的对象,每个属性都是一个包含测试用例的数组。

    ¥An object containing valid and invalid properties, each of which is an array containing test cases.

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

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

  • name(字符串,可选):用于测试用例的名称,以便于查找

    ¥name (string, optional): The name to use for the test case, to make it easier to find

  • code(字符串,必填):应运行规则的源代码

    ¥code (string, required): The source code that the rule should be run on

  • options(数组,可选):传递给规则的选项。规则严重性不应包含在此列表中。

    ¥options (array, optional): The options passed to the rule. The rule severity should not be included in this list.

  • filename(字符串,可选):给定案例的文件名(对于对文件名做出断言的规则很有用)。

    ¥filename (string, optional): The filename for the given case (useful for rules that make assertions about filenames).

  • only(布尔值,可选):运行此案例专门用于在支持的测试框架中进行调试。

    ¥only (boolean, optional): Run this case exclusively for debugging in supported test frameworks.

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

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

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

    ¥errors (number or array, required): Asserts some properties of the errors that the rule is expected to produce when run on this code. If this is a number, asserts the number of errors produced. Otherwise, this should be a list of objects, each containing information about a single reported error. The following properties can be used for an error (all are optional unless otherwise noted):

    • message(字符串/正则表达式):错误的消息。必须提供此或 messageId

      ¥message (string/regexp): The message for the error. Must provide this or messageId

    • messageId(字符串):错误的 ID。必须提供此或 message。详见 使用 messageId 测试错误

      ¥messageId (string): The Id for the error. Must provide this or message. See testing errors with messageId for details

    • data(对象):可与 messageId 结合使用的占位符数据

      ¥data (object): Placeholder data which can be used in combination with messageId

    • type(字符串):上报的 AST 节点类型

      ¥type (string): The type of the reported AST node

    • line(编号):报告位置的基于 1 的行号

      ¥line (number): The 1-based line number of the reported location

    • column(编号):报告位置的基于 1 的列号

      ¥column (number): The 1-based column number of the reported location

    • endLine(编号):报告位置结尾的基于 1 的行号

      ¥endLine (number): The 1-based line number of the end of the reported location

    • endColumn(编号):报告位置结尾的基于 1 的列号

      ¥endColumn (number): The 1-based column number of the end of the reported location

    • suggestions(数组):包含要检查的建议详细信息的对象数组。如果规则产生建议,则为必需。详见 测试建议

      ¥suggestions (array): An array of objects with suggestion details to check. Required if the rule produces suggestions. See Testing Suggestions for details

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

    ¥If a string is provided as an error instead of an object, the string is used to assert the message of the error.

  • output(字符串,如果规则修复代码则需要):断言使用此规则进行单次自动修复时将产生的输出(例如,使用 --fix 命令行标志)。如果这是 null 或被省略,则断言报告的问题均未建议自动修复。

    ¥output (string, required if the rule fixes code): Asserts the output that will be produced when using this rule for a single pass of autofixing (e.g. with the --fix command line flag). If this is null or omitted, asserts that none of the reported problems suggest autofixes.

测试用例的任何附加属性将作为配置选项直接传递给 linter。例如,一个测试用例可以有一个 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.

使用 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 不会断言 data 已传递给 context.report。相反,它用于形成预期的消息文本,然后将其与接收到的 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;。如果应用修复后的输出不匹配,则测试失败。

¥A 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

    ¥desc (string): The suggestion desc value. Must provide this or messageId

  • messageId(字符串):使用 messageId 的建议的建议 messageId 值。必须提供此或 desc

    ¥messageId (string): The suggestion messageId value for suggestions that use messageIds. Must provide this or desc

  • data(对象):可与 messageId 结合使用的占位符数据。

    ¥data (object): Placeholder data which can be used in combination with messageId.

  • output(字符串,必填):表示将建议修复应用于输入代码的结果的代码字符串

    ¥output (string, required): A code string representing the result of applying the suggestion fix to the input code

示例:

¥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 测试错误

¥messageId and data properties in suggestion test objects work the same way as in error test objects. See testing errors with messageId for details.

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。这些功能可以来自不同的地方:

¥RuleTester depends on two functions to run tests: describe and it. These functions can come from various places:

  1. 如果 RuleTester.describeRuleTester.it 已设置为功能值,则 RuleTester 将使用 RuleTester.describeRuleTester.it 运行测试。你可以使用它来自定义 RuleTester 的行为以匹配你正在使用的测试框架。

    ¥If RuleTester.describe and RuleTester.it have been set to function values, RuleTester will use RuleTester.describe and RuleTester.it to run tests. You can use this to customize the behavior of RuleTester to match a test framework that you’re using.

    如果 RuleTester.itOnly 已设置为函数值,则 RuleTester 将调用 RuleTester.itOnly 而不是 RuleTester.it 来运行 only: true 的案例。如果 RuleTester.itOnly 未设置,但 RuleTester.it 具有 only 功能属性,则 RuleTester 将退回到 RuleTester.it.only

    ¥If RuleTester.itOnly has been set to a function value, RuleTester will call RuleTester.itOnly instead of RuleTester.it to run cases with only: true. If RuleTester.itOnly is not set but RuleTester.it has an only function property, RuleTester will fall back to RuleTester.it.only.

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

    ¥Otherwise, if describe and it are present as globals, RuleTester will use globalThis.describe and globalThis.it to run tests and globalThis.it.only to run cases with only: true. This allows RuleTester to work when using frameworks like Mocha without any additional configuration.

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

    ¥Otherwise, RuleTester#run will simply execute all of the tests in sequence, and will throw an error if one of them fails. This means you can simply execute a test file that calls RuleTester.run using Node.js, without needing a testing framework.

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

¥RuleTester#run calls the describe function with two arguments: a string describing the rule, and a callback function. The callback calls the it function with a string describing the test case, and a test function. The test function will return successfully if the test passes, and throw an error if the test fails. The signature for only is the same as it. RuleTester calls either it or only for every case even when some cases have only: true, and the test framework is responsible for implementing test case exclusivity. (Note that this is the standard behavior for test suites when using frameworks like Mocha; this information is only relevant if you plan to customize RuleTester.describe, RuleTester.it, or RuleTester.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
    ]
})