迁移到 v9.x

ESLint v9.0.0 是 ESLint 的主要版本,因此有一些你需要注意的重大更改。本指南旨在引导你完成重大更改。

ESLint v9.0.0 is a major release of ESLint, and as such, has several breaking changes that you need to be aware of. This guide is intended to walk you through the breaking changes.

下面的列表大致按每个更改预计会影响的用户数量排序,其中第一个项目预计会影响最多的用户。

The lists below are ordered roughly by the number of users each change is expected to affect, where the first items are expected to affect the most users.

目录

Table of Contents

对用户的重大更改

Breaking changes for users

对插件开发者的重大更改

Breaking changes for plugin developers

对集成开发者的重大更改

Breaking changes for integration developers


Node.js < v18.18、v19 不再支持

Node.js < v18.18, v19 are no longer supported

从 ESLint v9.0.0 开始,ESLint 正式放弃对这些版本的 Node.js 的支持。ESLint 现在支持以下版本的 Node.js:

ESLint is officially dropping support for these versions of Node.js starting with ESLint v9.0.0. ESLint now supports the following versions of Node.js:

  • Node.js v18.18.0 及更高版本

    Node.js v18.18.0 and above

  • Node.js v20.9.0 及更高版本

    Node.js v20.9.0 and above

  • Node.js v21 及更高版本

    Node.js v21 and above

要解决:使用 ESLint v9.0.0 时,请确保至少升级到 Node.js v18.18.0。需要仔细检查的一件重要事情是通过编辑器集成使用 ESLint 时编辑器支持的 Node.js 版本。如果你无法升级,我们建议你继续使用 ESLint v8.56.0,直到你能够升级 Node.js。

To address: Make sure you upgrade to at least Node.js v18.18.0 when using ESLint v9.0.0. One important thing to double check is the Node.js version supported by your editor when using ESLint via editor integrations. If you are unable to upgrade, we recommend continuing to use ESLint v8.56.0 until you are able to upgrade Node.js.

相关问题):#17595

Related issue(s): #17595

新的默认配置格式 (eslint.config.js)

New default config format (eslint.config.js)

正如我们在 博客文章 中所宣布的,在 ESLint v9.0.0 中,eslint.config.js 是新的默认配置格式。以前的格式 eslintrc 现已弃用,并且不会自动搜索。

As announced in our blog post, in ESLint v9.0.0, eslint.config.js is the new default configuration format. The previous format, eslintrc, is now deprecated and will not automatically be searched for.

要解决:将你的配置更新为 配置迁移指南 后的新格式。如果你仍然需要使用已弃用的 eslintrc 配置格式,请将环境变量 ESLINT_USE_FLAT_CONFIG 设置为 false

To address: Update your configuration to the new format following the Configuration Migration Guide. In case you still need to use the deprecated eslintrc config format, set environment variable ESLINT_USE_FLAT_CONFIG to false.

相关问题:#13481

Related Issues(s): #13481

删除了多个格式化程序

Removed multiple formatters

ESLint v9.0.0 已从核心中删除了以下格式化程序:

ESLint v9.0.0 has removed the following formatters from the core:

删除格式化程序 替换 npm 包
checkstyle eslint-formatter-checkstyle
compact eslint-formatter-compact
jslint-xml eslint-formatter-jslint-xml
junit eslint-formatter-junit
tap eslint-formatter-tap
unix eslint-formatter-unix
visualstudio eslint-formatter-visualstudio

要解决:如果你通过 -f 命令行标志使用这些格式化程序中的任何一个,则需要为格式化程序安装相应的包。

To address: If you are using any of these formatters via the -f command line flag, you’ll need to install the respective package for the formatter.

相关问题):#17524

Related issue(s): #17524

删除了 require-jsdocvalid-jsdoc 规则

Removed require-jsdoc and valid-jsdoc rules

require-jsdocvalid-jsdoc 规则已在 ESLint v9.0.0 中删除。这些规则最初于 2018 年被废弃。

The require-jsdoc and valid-jsdoc rules have been removed in ESLint v9.0.0. These rules were initially deprecated in 2018.

要解决:在 eslint-plugin-jsdoc 中使用 更换规则

To address: Use the replacement rules in eslint-plugin-jsdoc.

相关问题):#15820

Related issue(s): #15820

eslint:recommended 已更新

eslint:recommended has been updated

eslint:recommended 中启用了四项新规则:

Four new rules have been enabled in eslint:recommended:

此外,以下规则已从 eslint:recommended 中删除:

Additionally, the following rules have been removed from eslint:recommended:

要解决:修复错误或禁用这些规则。

To address: Fix errors or disable these rules.

相关问题):#15576, #17446, #17596

Related issue(s): #15576, #17446, #17596

--quiet 不再运行设置为 "warn" 的规则

--quiet no longer runs rules set to "warn"

在 ESLint v9.0.0 之前,--quiet CLI 标志将运行设置为 "error""warn" 的所有规则,然后隐藏设置为 "warn" 的规则的结果。在 ESLint v9.0.0 中,--quiet 设置为 "warn" 时将阻止规则执行。这可以提高包含许多设置为 "warn" 的规则的配置的性能。

Prior to ESLint v9.0.0, the --quiet CLI flag would run all rules set to either "error" or "warn" and then hide the results from rules set to "warn". In ESLint v9.0.0, --quiet will prevent rules from being executed when set to "warn". This can result in a performance improvement for configurations containing many rules set to "warn".

如果使用 --max-warnings,则 --quiet 将不会抑制设置为 "warn" 的规则的执行,但这些规则的输出将被抑制。

If --max-warnings is used then --quiet will not suppress the execution of rules set to "warn" but the output of those rules will be suppressed.

要解决:在大多数情况下,这种变化是透明的。但是,如果你运行设置为 "warn" 的规则,使数据更改可供其他规则使用(例如,如果规则使用 sourceCode.markVariableAsUsed()),则这可能会导致行为更改。在这种情况下,你需要将规则设置为 "error" 或停止使用 --quiet

To address: In most cases, this change is transparent. If, however, you are running a rule set to "warn" that makes changes to the data available to other rules (for example, if the rule uses sourceCode.markVariableAsUsed()), then this can result in a behavior change. In such a case, you’ll need to either set the rule to "error" or stop using --quiet.

相关问题):#16450

Related issue(s): #16450

--output-file 现在即使输出为空也会将文件写入磁盘

--output-file now writes a file to disk even with an empty output

在 ESLint v9.0.0 之前,如果输出为空,--output-file 标志将跳过将文件写入磁盘。但是,在 ESLint v9.0.0 中,--output-file 现在始终将文件写入磁盘,即使输出为空也是如此。此更新确保 --output-file 的行为更加一致和可靠。

Prior to ESLint v9.0.0, the --output-file flag would skip writing a file to disk if the output was empty. However, in ESLint v9.0.0, --output-file now consistently writes a file to disk, even when the output is empty. This update ensures a more consistent and reliable behavior for --output-file.

要解决:检查 --output-file 标志的使用情况,尤其是当你的进程取决于基于输出内容的文件是否存在时。如有必要,请更新你的脚本或配置以适应此更改。

To address: Review your usage of the --output-file flag, especially if your processes depend on the file’s presence or absence based on output content. If necessary, update your scripts or configurations to accommodate this change.

相关问题:#17660

Related Issues(s): #17660

没有模式传递到 CLI 时行为发生变化

Change in behavior when no patterns are passed to CLI

在 ESLint v9.0.0 之前,在没有任何文件或目录模式的情况下运行 ESLint CLI 将导致没有文件被 linted,并会以代码 0 退出。这很令人困惑,因为不清楚实际上什么都没有发生。在 ESLint v9.0.0 中,此行为已更新:

Prior to ESLint v9.0.0, running the ESLint CLI without any file or directory patterns would result in no files being linted and would exit with code 0. This was confusing because it wasn’t clear that nothing had actually happened. In ESLint v9.0.0, this behavior has been updated:

  • 扁平配置。如果你使用扁平配置,则可以运行 npx eslinteslint(如果全局安装),ESLint 会假设你想要对当前目录进行 lint 检测。实际上,不通过任何模式相当于通过 .

    Flat config. If you are using flat config, you can run npx eslint or eslint (if globally installed) and ESLint will assume you want to lint the current directory. Effectively, passing no patterns is equivalent to passing ..

  • eslintrc。如果你使用已弃用的 eslintrc 配置,那么在运行没有任何模式的 CLI 时,你现在会收到错误。

    eslintrc. If you are using the deprecated eslintrc config, you’ll now receive an error when running the CLI without any patterns.

要解决:在大多数情况下,无需进行任何更改,并且你可能会发现某些位置你认为 ESLint 正在运行,但实际上并未运行。如果你想保留 v8.x 行为(不传递任何模式会导致 ESLint 以代码 0 退出),请将 --pass-on-no-patterns 标志添加到 CLI 调用中。

To address: In most cases, no change is necessary, and you may find some locations where you thought ESLint was running but it wasn’t. If you’d like to keep the v8.x behavior, where passing no patterns results in ESLint exiting with code 0, add the --pass-on-no-patterns flag to the CLI call.

相关问题):#14308

Related issue(s): #14308

仅具有严重性的 /* eslint */ 注释现在保留配置文件中的选项

/* eslint */ comments with only severity now retain options from the config file

在 ESLint v9.0.0 之前,配置注释(例如 /* eslint curly: "warn" *//* eslint curly: ["warn"] */)将完全覆盖配置文件中为规则指定的任何配置,从而强制执行规则的默认选项。

Prior to ESLint v9.0.0, configuration comments such as /* eslint curly: "warn" */ or /* eslint curly: ["warn"] */ would completely override any configuration specified for the rule in the config file, and thus enforce the default options of the rule.

在 ESLint v9.0.0 中,配置注释的行为与配置文件中规则配置的合并方式一致,这意味着仅具有严重性的配置注释现在保留配置文件中指定的选项,并且仅覆盖严重性。

In ESLint v9.0.0, the behavior of configuration comments is aligned with how rule configurations in config files are merged, meaning that a configuration comment with only severity now retains options specified in the config file and just overrides the severity.

例如,如果你有以下配置文件:

For example, if you have the following config file:

// eslint.config.js

export default [{
    rules: {
        curly: ["error", "multi"]
    }
}];

以及以下配置注释:

and the following configuration comment:

// my-file.js

/* eslint curly: "warn" */

当检查 my-file.js 时,curly 规则的结果配置将是 curly: ["warn", "multi"]

the resulting configuration for the curly rule when linting my-file.js will be curly: ["warn", "multi"].

请注意,此更改仅影响在带有选项的配置文件中配置相同规则以及使用不带选项的配置注释的情况。在所有其他情况下(例如,仅使用配置注释配置规则),行为与 ESLint v9.0.0 之前的行为保持相同。

Note that this change only affects cases where the same rule is configured in the config file with options and using a configuration comment without options. In all other cases (e.g. the rule is only configured using a configuration comment), the behavior remains the same as prior to ESLint v9.0.0.

要解决:我们预计在大多数情况下不需要进行任何更改,因为使用配置注释配置的规则通常尚未在配置文件中配置。但是,如果你需要配置注释来完全覆盖配置文件中的配置并强制执行默认选项,则需要至少指定一个选项:

To address: We expect that in most cases no change is necessary, as rules configured using configuration comments are typically not already configured in the config file. However, if you need a configuration comment to completely override configuration from the config file and enforce the default options, you’ll need to specify at least one option:

// my-file.js

/* eslint curly: ["warn", "all"] */

相关问题):#17381

Related issue(s): #17381

更严格的 /* exported */ 解析

Stricter /* exported */ parsing

在 ESLint v9.0.0 之前,/* exported */ 指令错误地允许以下语法:

Prior to ESLint v9.0.0, the /* exported */ directive incorrectly allowed the following syntax:

/* exported foo: true, bar: false */

// and

/* exported foo bar */

本例中的 truefalse 对 ESLint 的行为没有影响,事实上,这是一个解析错误。

The true and false in this example had no effect on ESLint’s behavior, and in fact, was a parsing bug.

在 ESLint v9.0.0 中,任何后跟冒号和值的 /* exported */ 变量都将被视为无效而被忽略。

In ESLint v9.0.0, any /* exported */ variables followed by a colon and value will be ignored as invalid.

要解决:更新任何 /* exported */ 指令以消除冒号和后续值,并确保变量名称之间有逗号,例如:

To address: Update any /* exported */ directives to eliminate the colons and subsequent values, and ensure there are commas between variable names such as:

/* exported foo, bar */

相关问题):#17622

Related issue(s): #17622

no-constructor-returnno-sequences 规则模式更严格

no-constructor-return and no-sequences rule schemas are stricter

在 ESLint 的早期版本中,no-constructor-returnno-sequences 规则错误地接受无效选项。

In previous versions of ESLint, no-constructor-return and no-sequences rules were mistakenly accepting invalid options.

这已在 ESLint v9.0.0 中修复:

This has been fixed in ESLint v9.0.0:

  • no-constructor-return 规则不接受任何选项。

    The no-constructor-return rule does not accept any options.

  • no-sequences 规则可以采用一个选项,即具有属性 "allowInParentheses"(布尔值)的对象。

    The no-sequences rule can take one option, an object with a property "allowInParentheses" (boolean).

{
    "rules": {
        "no-constructor-return": ["error"],
        "no-sequences": ["error", { "allowInParentheses": false }]
    }
}

要解决:如果 ESLint 报告任何这些规则的配置无效,请更新你的配置。

To address: If ESLint reports invalid configuration for any of these rules, update your configuration.

相关问题):#16879

Related issue(s): #16879

默认情况下 no-implicit-coercion 中的新检查

New checks in no-implicit-coercion by default

在 ESLint v9.0.0 中,no-implicit-coercion 规则默认额外报告以下情况:

In ESLint v9.0.0, the no-implicit-coercion rule additionally reports the following cases by default:

-(-foo);
foo - 0;

要解决:如果你想保留此规则之前的行为,请设置 "allow": ["-", "- -"]

To address: If you want to retain the previous behavior of this rule, set "allow": ["-", "- -"].

{
    "rules": {
        "no-implicit-coercion": [2, { "allow": ["-", "- -"] } ],
    }
}

相关问题):#17832

Related issue(s): #17832

no-invalid-regexp 中区分大小写的标志

Case-sensitive flags in no-invalid-regexp

在 ESLint v9.0.0 中,选项 allowConstructorFlags 现在区分大小写。

In ESLint v9.0.0, the option allowConstructorFlags is now case-sensitive.

要解决:如果需要,请更新你的配置。

To address: Update your configuration if needed.

相关问题):#16574

Related issue(s): #16574

no-unused-vars varsIgnorePattern 选项不再适用于 catch 参数

varsIgnorePattern option of no-unused-vars no longer applies to catch arguments

在 ESLint 的早期版本中,no-unused-varsvarsIgnorePattern 选项错误地忽略了 catch 子句中指定的错误。在 ESLint v9.0.0 中,varsIgnorePattern 不再适用于 catch 子句中的错误。例如:

In previous versions of ESLint, the varsIgnorePattern option of no-unused-vars incorrectly ignored errors specified in a catch clause. In ESLint v9.0.0, varsIgnorePattern no longer applies to errors in catch clauses. For example:

/*eslint no-unused-vars: ["error", { "caughtErrors": "all", "varsIgnorePattern": "^err" }]*/

try {
    //...
} catch (err) { // 'err' will be reported.
    console.error("errors");
}

要解决:如果要为 catch 子句变量名称指定忽略模式,除了 varsIgnorePattern 之外,还可以使用 caughtErrorsIgnorePattern 选项。

To address: If you want to specify ignore patterns for catch clause variable names, use the caughtErrorsIgnorePattern option in addition to varsIgnorePattern.

相关问题):#17540

Related issue(s): #17540

no-restricted-imports 现在接受具有相同 name 的多个配置条目

no-restricted-imports now accepts multiple config entries with the same name

在 ESLint 的早期版本中,如果 no-restricted-imports 规则配置的 paths 数组中的多个条目具有相同的 name 属性,则只有最后一个会应用,而之前的条目将被忽略。

In previous versions of ESLint, if multiple entries in the paths array of your configuration for the no-restricted-imports rule had the same name property, only the last one would apply, while the previous ones would be ignored.

从 ESLint v9.0.0 开始,所有条目都适用,允许为不同的导入名称指定不同的消息。例如,你现在可以像这样配置规则:

As of ESLint v9.0.0, all entries apply, allowing for specifying different messages for different imported names. For example, you can now configure the rule like this:

{
    rules: {
        "no-restricted-imports": ["error", {
            paths: [
                {
                    name: "react-native",
                    importNames: ["Text"],
                    message: "import 'Text' from 'ui/_components' instead"
                },
                {
                    name: "react-native",
                    importNames: ["View"],
                    message: "import 'View' from 'ui/_components' instead"
                }
            ]
        }]
    }
}

并且 import { Text } from "react-native"import { View } from "react-native" 都会被报告,并带有不同的消息。

and both import { Text } from "react-native" and import { View } from "react-native" will be reported, with different messages.

在 ESLint 的早期版本中,使用此配置只会报告 import { View } from "react-native"

In previous versions of ESLint, with this configuration only import { View } from "react-native" would be reported.

要解决:如果你对此规则的配置有多个具有相同 name 的条目,你可能需要删除无意的条目。

To address: If your configuration for this rule has multiple entries with the same name, you may need to remove unintentional ones.

相关问题):#15261

Related issue(s): #15261

扁平配置中不再接受 "eslint:recommended""eslint:all"

"eslint:recommended" and "eslint:all" no longer accepted in flat config

在 ESLint v8.x 中,eslint.config.js 可以通过将字符串插入到配置数组中来引用 "eslint:recommended""eslint:all" 配置,如下例所示:

In ESLint v8.x, eslint.config.js could refer to "eslint:recommended" and "eslint:all" configurations by inserting a string into the config array, as in this example:

// eslint.config.js
export default [
    "eslint:recommended",
    "eslint:all"
];

在 ESLint v9.0.0 中,不再支持此格式,并且会导致错误。

In ESLint v9.0.0, this format is no longer supported and will result in an error.

要解决:使用 @eslint/js 包代替:

To address: Use the @eslint/js package instead:

// eslint.config.js
import js from "@eslint/js";

export default [
    js.configs.recommended,
    js.configs.all
];

相关问题):#17488

Related issue(s): #17488

no-inner-declarations 有一个新的默认行为和一个新选项

no-inner-declarations has a new default behavior with a new option

ESLint v9.0.0 在 no-inner-declarations 规则中引入了一个名为 blockScopeFunctions 的新选项,当 languageOptions.ecmaVersion 设置为 2015 或更高时,默认情况下允许在严格模式下使用块级 function

ESLint v9.0.0 introduces a new option in no-inner-declarations rule called blockScopeFunctions which by default allows block-level functions in strict mode when languageOptions.ecmaVersion is set to 2015 or above.

/*eslint no-inner-declarations: "error"*/
"use strict";

if (test) {
    function foo () { }  // no error
}

要解决:如果要报告每种条件下的块级 function,无论严格模式还是非严格模式,请将 blockScopeFunctions 选项设置为 "disallow"

To address: If you want to report the block-level functions in every condition regardless of strict or non-strict mode, set the blockScopeFunctions option to "disallow".

相关问题):#15576

Related issue(s): #15576

no-unused-vars 现在默认为 caughtErrors"all"

no-unused-vars now defaults caughtErrors to "all"

ESLint v9.0.0 更改了 no-unused-vars 规则的 caughtErrors 选项的默认值。以前它默认为 "none",从不检查是否使用了捕获的错误。现在默认为 "all" 以检查捕获的错误是否被使用。

ESLint v9.0.0 changes the default value for the no-unused-vars rule’s caughtErrors option. Previously it defaulted to "none" to never check whether caught errors were used. It now defaults to "all" to check caught errors for being used.

/*eslint no-unused-vars: "error"*/
try {}
catch (error) {
    // 'error' is defined but never used
}

要解决:如果要允许未使用的捕获错误,例如编写将直接在不支持 ES2019 可选 catch 绑定的环境中运行的代码时,请将 caughtErrors 选项设置为 "none"。否则,删除未使用的捕获错误。

To address: If you want to allow unused caught errors, such as when writing code that will be directly run in an environment that does not support ES2019 optional catch bindings, set the caughtErrors option to "none". Otherwise, delete the unused caught errors.

/*eslint no-unused-vars: "error"*/
try {}
catch {
    // no error
}

相关问题):#17974

Related issue(s): #17974

no-useless-computed-key 默认标记类中不必要的计算成员名称

no-useless-computed-key flags unnecessary computed member names in classes by default

在 ESLint v9.0.0 中,no-useless-computed-key 规则的 enforceForClassMembers 选项的默认值从 false 更改为 true。此更改的效果是默认情况下将标记类中不必要的计算成员名称。

In ESLint v9.0.0, the default value of the enforceForClassMembers option of the no-useless-computed-key rule was changed from false to true. The effect of this change is that unnecessary computed member names in classes will be flagged by default.

/*eslint no-useless-computed-key: "error"*/

class SomeClass {
    ["someMethod"]() {} // ok in ESLint v8, error in ESLint v9.
}

要解决:通过将 enforceForClassMembers 选项设置为 false,修复规则报告的问题或恢复到以前的行为。

To address: Fix the problems reported by the rule or revert to the previous behavior by setting the enforceForClassMembers option to false.

相关问题):#18042

Related issue(s): #18042

删除了多个 context 方法

Removed multiple context methods

ESLint v9.0.0 从 context 对象中删除了多个已弃用的方法,并将它们移动到 SourceCode 对象上:

ESLint v9.0.0 removes multiple deprecated methods from the context object and moves them onto the SourceCode object:

context 上删除 SourceCode 上替代
context.getSource() sourceCode.getText()
context.getSourceLines() sourceCode.getLines()
context.getAllComments() sourceCode.getAllComments()
context.getNodeByRangeIndex() sourceCode.getNodeByRangeIndex()
context.getComments() sourceCode.getCommentsBefore(), sourceCode.getCommentsAfter(), sourceCode.getCommentsInside()
context.getCommentsBefore() sourceCode.getCommentsBefore()
context.getCommentsAfter() sourceCode.getCommentsAfter()
context.getCommentsInside() sourceCode.getCommentsInside()
context.getJSDocComment() sourceCode.getJSDocComment()
context.getFirstToken() sourceCode.getFirstToken()
context.getFirstTokens() sourceCode.getFirstTokens()
context.getLastToken() sourceCode.getLastToken()
context.getLastTokens() sourceCode.getLastTokens()
context.getTokenAfter() sourceCode.getTokenAfter()
context.getTokenBefore() sourceCode.getTokenBefore()
context.getTokenByRangeStart() sourceCode.getTokenByRangeStart()
context.getTokens() sourceCode.getTokens()
context.getTokensAfter() sourceCode.getTokensAfter()
context.getTokensBefore() sourceCode.getTokensBefore()
context.getTokensBetween() sourceCode.getTokensBetween()
context.parserServices sourceCode.parserServices
context.getDeclaredVariables() sourceCode.getDeclaredVariables()

除了上表中的方法之外,还有其他几个方法也被移动,但需要不同的方法签名:

In addition to the methods in the above table, there are several other methods that are also moved but required different method signatures:

context 上删除 SourceCode 上替代
context.getAncestors() sourceCode.getAncestors(node)
context.getScope() sourceCode.getScope(node)
context.markVariableAsUsed(name) sourceCode.markVariableAsUsed(name, node)

要解决:遵循 博客文章 中的建议。

To address: Following the recommendations in the blog post.

相关问题:#16999, #13481

Related Issues(s): #16999, #13481

删除 sourceCode.getComments()

Removed sourceCode.getComments()

ESLint v9.0.0 删除了已弃用的 sourceCode.getComments() 方法。

ESLint v9.0.0 removes the deprecated sourceCode.getComments() method.

要解决:替换为 sourceCode.getCommentsBefore()sourceCode.getCommentsAfter()sourceCode.getCommentsInside()

To address: Replace with sourceCode.getCommentsBefore(), sourceCode.getCommentsAfter(), or sourceCode.getCommentsInside().

相关问题:#14744

Related Issues(s): #14744

删除 CodePath#currentSegments

Removed CodePath#currentSegments

ESLint v9.0.0 删除了已弃用的 CodePath#currentSegments 属性。

ESLint v9.0.0 removes the deprecated CodePath#currentSegments property.

要解决:按照 博客文章 中的建议更新你的代码。

To address: Update your code following the recommendations in the blog post.

相关问题:#17457

Related Issues(s): #17457

不再支持函数式规则

Function-style rules are no longer supported

ESLint v9.0.0 放弃了对函数式规则的支持。函数式规则是通过导出函数而不是具有 create() 方法的对象来创建的规则。此规则格式已于 2016 年弃用。

ESLint v9.0.0 drops support for function-style rules. Function-style rules are rules created by exporting a function rather than an object with a create() method. This rule format was deprecated in 2016.

要解决:将你的规则更新为 最新的规则格式

To address: Update your rules to the most recent rule format.

eslint-plugin/prefer-object-rule 规则可以帮助强制使用对象样式规则并自动修复任何剩余的函数样式规则。

The eslint-plugin/prefer-object-rule rule can help enforce the usage of object-style rules and autofix any remaining function-style rules.

相关问题:#14709

Related Issues(s): #14709

对于带有选项的规则,需要 meta.schema

meta.schema is required for rules with options

从 ESLint v9.0.0 开始,如果任何选项是 passed 到未指定 meta.schema 属性的规则,则会抛出错误。

As of ESLint v9.0.0, an error will be thrown if any options are passed to a rule that doesn’t specify meta.schema property.

要解决:

To address:

  • 如果你的规则需要 选项,请将 meta.schema 属性设置为规则选项的 JSON 架构格式描述。ESLint 将使用此架构来验证配置的选项并防止对规则的无效或意外输入。

    If your rule expects options, set meta.schema property to a JSON Schema format description of the rule’s options. This schema will be used by ESLint to validate configured options and prevent invalid or unexpected inputs to your rule.

  • 如果你的规则不需要任何选项,则无需执行任何操作。此更改可确保终端用户不会错误地为不需要选项的规则配置选项。

    If your rule doesn’t expect any options, there is no action required. This change ensures that end users will not mistakenly configure options for rules that don’t expect options.

  • (不推荐)你还可以将 meta.schema 设置为 false 以禁用此验证,但强烈建议如果规则需要选项,则提供架构;如果规则不需要选项,则强烈建议忽略架构(或设置 []),以便 ESLint 可以确保你的用户的配置有效。

    (not recommended) you can also set meta.schema to false to disable this validation, but it is highly recommended to provide a schema if the rule expects options and omit the schema (or set []) if the rule doesn’t expect options so that ESLint can ensure that your users’ configurations are valid.

eslint-plugin/require-meta-schema 规则可以帮助强制规则在需要时具有架构。

The eslint-plugin/require-meta-schema rule can help enforce that rules have schemas when required.

相关问题:#14709

Related Issues(s): #14709

FlatRuleTester 现在是 RuleTester

FlatRuleTester is now RuleTester

正如我们在 博客文章 中所宣布的,临时 FlatRuleTester 类已重命名为 RuleTester,而 v8.x 中的 RuleTester 类已被删除。此外,eslint/use-at-your-own-risk 中的 FlatRuleTester 导出已被删除。

As announced in our blog post, the temporary FlatRuleTester class has been renamed to RuleTester, while the RuleTester class from v8.x has been removed. Additionally, the FlatRuleTester export from eslint/use-at-your-own-risk has been removed.

要解决:更新你的规则测试以使用新的 RuleTester。为此,你需要进行以下一些常见更改:

To address: Update your rule tests to use the new RuleTester. To do so, here are some of the common changes you’ll need to make:

  • 请注意 ecmaVersionsourceType 的新默认值。默认情况下,RuleTester 使用 ecmaVersion: "latest"sourceType: "module" 的扁平配置默认值。如果某些测试期望使用旧的默认值 ecmaVersion: 5sourceType: "script",这可能会导致某些测试失败。如果你想使用旧的默认值,则需要在 RuleTester 中手动指定,如下所示:

    Be aware of new defaults for ecmaVersion and sourceType. By default, RuleTester uses the flat config default of ecmaVersion: "latest" and sourceType: "module". This may cause some tests to break if they were expecting the old default of ecmaVersion: 5 and sourceType: "script". If you’d like to use the old default, you’ll need to manually specify that in your RuleTester like this:

    // use eslintrc defaults
    const ruleTester = new RuleTester({
        languageOptions: {
            ecmaVersion: 5,
            sourceType: "script"
        }
    });
    
  • parserOptions 更改为 languageOptions。如果你在测试中设置 ecmaVersionsourceType,请将它们从 parserOptions 移至 languageOptions,如下所示:

    Change parserOptions to languageOptions. If you’re setting ecmaVersion or sourceType on your tests, move those from parserOptions to languageOptions, like this:

    ruleTester.run("my-rule", myRule, {
        valid: [
            {
                code: "foo",
                parserOptions: {
                    ecmaVersion: 6
                }
            }
        ]
    });
    
    // becomes
    
    ruleTester.run("my-rule", myRule, {
        valid: [
            {
                code: "foo",
                languageOptions: {
                    ecmaVersion: 6
                }
            }
        ]
    });
    
  • 翻译其他配置键。用于在 eslintrc 配置系统上运行的 envparser 等键必须转换为扁平配置系统。有关转换你可能使用的其他按键的详细信息,请参阅 配置迁移指南

    Translate other config keys. Keys such as env and parser that used to run on the eslintrc config system must be translated into the flat config system. Please refer to the Configuration Migration Guide for details on translating other keys you may be using.

相关问题:#13481

Related Issues(s): #13481

更严格的 RuleTester 检查

Stricter RuleTester checks

为了帮助开发没有常见错误的高质量自定义规则,ESLint v9.0.0 对 RuleTester 进行了几项更改:

In order to aid in the development of high-quality custom rules that are free from common bugs, ESLint v9.0.0 implements several changes to RuleTester:

  1. 测试用例 output 必须与 code 不同。在 ESLint v8.x 中,如果 outputcode 相同,则断言没有自动修复。在查看测试用例时,并不总是立即清楚 output 是否与 code 不同,特别是当字符串较长或多行时,这使得开发者很难确定测试用例是否需要自动修复。在 ESLint v9.0.0 中,为了避免这种歧义,如果测试 output 与测试 code 具有相同的值,RuleTester 现在会抛出错误。因此,现在指定 output 必然意味着测试用例需要自动修复并断言其结果。如果测试用例不需要自动修复,请忽略 output 属性或将其设置为 null。这断言没有自动修复。

    Test case output must be different from code. In ESLint v8.x, if output is the same as code, it asserts that there was no autofix. When looking at a test case, it’s not always immediately clear whether output differs from code, especially if the strings are longer or multiline, making it difficult for developers to determine whether or not the test case expects an autofix. In ESLint v9.0.0, to avoid this ambiguity, RuleTester now throws an error if the test output has the same value as the test code. Therefore, specifying output now necessarily means that the test case expects an autofix and asserts its result. If the test case doesn’t expect an autofix, omit the output property or set it to null. This asserts that there was no autofix.

  2. 测试错误对象必须指定 messagemessageId。为了提高测试覆盖率的质量,如果测试错误对象上既没有指定 message 也没有指定 messageIdRuleTester 现在会引发错误。

    Test error objects must specify message or messageId. To improve the quality of test coverage, RuleTester now throws an error if neither message nor messageId is specified on test error objects.

  3. 如果实际错误提供建议,测试错误对象必须指定 suggestions。在 ESLint v8.x 中,如果测试错误对象中省略了 suggestions 属性,则 RuleTester 不会执行任何与建议相关的检查,因此很容易忘记断言测试用例是否产生建议。在 ESLint v9.0.0 中,省略 suggestions 属性断言实际错误不提供建议,而如果实际错误确实提供建议,则需要指定 suggestions 属性。我们强烈建议你通过指定测试建议对象数组来详细测试建议,但你也可以指定 suggestions: <number> 来仅断言建议的数量。

    Test error object must specify suggestions if the actual error provides suggestions. In ESLint v8.x, if the suggestions property was omitted from test error objects, RuleTester wasn’t performing any checks related to suggestions, so it was easy to forget to assert if a test case produces suggestions. In ESLint v9.0.0, omitting the suggestions property asserts that the actual error does not provide suggestions, while you need to specify the suggestions property if the actual error does provide suggestions. We highly recommend that you test suggestions in detail by specifying an array of test suggestion objects, but you can also specify suggestions: <number> to assert just the number of suggestions.

  4. 测试建议对象必须指定 output。为了提高测试覆盖率的质量,如果未在测试建议对象上指定 output 属性,RuleTester 现在会引发错误。

    Test suggestion objects must specify output. To improve the quality of test coverage, RuleTester now throws an error if output property is not specified on test suggestion objects.

  5. 测试建议对象必须指定 descmessageId。为了提高测试覆盖率的质量,如果测试建议对象上未指定 descmessageId 属性,RuleTester 现在会引发错误。也不允许同时指定两者。如果除了 messageId 之外你还想断言建议描述文本,那么还需要添加 data 属性。

    Test suggestion objects must specify desc or messageId. To improve the quality of test coverage, RuleTester now throws an error if neither desc nor messageId property is specified on test suggestion objects. It’s also not allowed to specify both. If you want to assert the suggestion description text in addition to the messageId, then also add the data property.

  6. 建议消息必须是唯一的。由于建议通常在编辑器中显示为下拉列表,因此针对同一 lint 问题的两个建议不能具有相同的消息,这一点很重要。否则,不可能知道任何给定的建议会起到什么作用。此附加检查会自动运行。

    Suggestion messages must be unique. Because suggestions are typically displayed in an editor as a dropdown list, it’s important that no two suggestions for the same lint problem have the same message. Otherwise, it’s impossible to know what any given suggestion will do. This additional check runs automatically.

  7. 建议必须修改代码。预计建议通过更改代码来解决报告的问题。如果建议测试 output 与测试 code 相同,RuleTester 现在会引发错误。

    Suggestions must change the code. Suggestions are expected to fix the reported problem by changing the code. RuleTester now throws an error if the suggestion test output is the same as the test code.

  8. 建议必须生成有效的语法。为了使规则建议有用,它们必须是有效的语法。RuleTester 现在使用与 code 值相同的语言选项来解析建议的输出,如果解析失败,则会抛出错误。

    Suggestions must generate valid syntax. In order for rule suggestions to be helpful, they need to be valid syntax. RuleTester now parses the output of suggestions using the same language options as the code value and throws an error if parsing fails.

  9. 测试用例必须是唯一的。相同的测试用例可能会导致混乱,并且很难在长测试文件中手动检测到。现在可以自动检测重复项并安全删除。

    Test cases must be unique. Identical test cases can cause confusion and be hard to detect manually in a long test file. Duplicates are now automatically detected and can be safely removed.

  10. filenameonly 必须是预期的类型。RuleTester 现在检查测试对象的 filenameonly 属性的类型。如果指定,filename 必须是字符串值。如果指定,only 必须是布尔值。

    filename and only must be of the expected type. RuleTester now checks the type of filename and only properties of test objects. If specified, filename must be a string value. If specified, only must be a boolean value.

要解决:使用 RuleTester 运行规则测试并修复发生的任何错误。为了满足 RuleTester 需要进行的更改与 ESLint v8.x 兼容。

To address: Run your rule tests using RuleTester and fix any errors that occur. The changes you’ll need to make to satisfy RuleTester are compatible with ESLint v8.x.

相关问题:#15104, #15735, #16908

Related Issues(s): #15104, #15735, #16908

FlatESLint 现在是 ESLint

FlatESLint is now ESLint

正如我们在 博客文章 中所宣布的,临时 FlatESLint 类已重命名为 ESLint,而 v8.x 中的 ESLint 类已重命名为 LegacyESLint

As announced in our blog post, the temporary FlatESLint class has been renamed to ESLint, while the ESLint class from v8.x has been renamed to LegacyESLint.

要解决:如果你当前正在使用 ESLint 类,请使用新的 ESLint 类验证你的测试是否通过。并非所有旧选项都受支持,因此你可能需要更新传递给构造函数的参数。有关详细信息,请参见 Node.js API 参考

To address: If you are currently using the ESLint class, verify that your tests pass using the new ESLint class. Not all of the old options are supported, so you may need to update the arguments passed to the constructor. See the Node.js API Reference for details.

如果你仍然需要 v8.x ESLint 功能,请使用 LegacyESLint 类,如下所示:

If you still need the v8.x ESLint functionality, use the LegacyESLint class like this:

const { LegacyESLint } = require("eslint/use-at-your-own-risk");

相关问题:#13481

Related Issues(s): #13481

Linter 现在需要扁平配置格式

Linter now expects flat config format

在 ESLint v9.0.0 中,传递给 Linter#verify()Linter#verifyAndFix() 方法的 config 参数应采用扁平配置格式。

In ESLint v9.0.0, the config argument passed to Linter#verify() and Linter#verifyAndFix() methods should be in the flat config format.

此外,方法 Linter#defineRule()Linter#defineRules()Linter#defineParser()Linter#getRules() 不再可用。

Additionally, methods Linter#defineRule(), Linter#defineRules(), Linter#defineParser(), and Linter#getRules() are no longer available.

要解决:如果你使用的是 Linter 类,请验证你的测试是否通过。

To address: If you are using the Linter class, verify that your tests pass.

如果你传递与扁平配置格式不兼容的配置对象,则需要更新代码。

If you’re passing configuration objects that are incompatible with the flat config format, you’ll need to update the code.

// eslintrc config format
linter.verify(code, {
    parserOptions: {
        ecmaVersion: 6
    }
});

// flat config format
linter.verify(code, {
    languageOptions: {
        ecmaVersion: 6
    }
});

有关转换你可能使用的其他按键的详细信息,请参阅 配置迁移指南

Please refer to the Configuration Migration Guide for details on translating other keys you may be using.

规则和解析器可以直接在配置中定义。

Rules and parsers can be defined directly in the configuration.

// eslintrc mode
linter.defineRule("my-rule1", myRule1);
linter.defineRules({
    "my-rule2": myRule2,
    "my-rule3": myRule3
});
linter.defineParser("my-parser", myParser);
linter.verify(code, {
    rules: {
        "my-rule1": "error",
        "my-rule2": "error",
        "my-rule3": "error"
    },
    parser: "my-parser"
});

// flat config mode
linter.verify(code, {
    plugins: {
        "my-plugin-foo": {
            rules: {
                "my-rule1": myRule1
            }
        },
        "my-plugin-bar": {
            rules: {
                "my-rule2": myRule2,
                "my-rule3": myRule3
            }
        }
    },
    rules: {
        "my-plugin-foo/my-rule1": "error",
        "my-plugin-bar/my-rule2": "error",
        "my-plugin-bar/my-rule3": "error"
    },
    languageOptions: {
        parser: myParser
    }
});

如果你仍然需要 v8.x Linter 功能,请将 configType: "eslintrc" 传递给构造函数,如下所示:

If you still need the v8.x Linter functionality, pass configType: "eslintrc" to the constructor like this:

const linter = new Linter({ configType: "eslintrc" });

linter.verify(code, {
    parserOptions: {
        ecmaVersion: 6
    }
});

linter.getRules();

相关问题:#13481

Related Issues(s): #13481

ESLint 中文网
粤ICP备13048890号