迁移到 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
-
--output-file
现在即使输出为空也会将文件写入磁盘¥
--output-file
now writes a file to disk even with an empty output -
仅具有严重性的
/* eslint */
注释现在保留配置文件中的选项¥
/* eslint */
comments with only severity now retain options from the config file -
现在不允许对同一规则进行多个
/* eslint */
注释¥Multiple
/* eslint */
comments for the same rule are now disallowed -
no-constructor-return
和no-sequences
规则模式更严格¥
no-constructor-return
andno-sequences
rule schemas are stricter -
no-unused-vars
的varsIgnorePattern
选项不再适用于 catch 参数¥
varsIgnorePattern
option ofno-unused-vars
no longer applies to catch arguments -
no-restricted-imports
现在接受具有相同name
的多个配置条目¥
no-restricted-imports
now accepts multiple config entries with the samename
-
扁平配置中不再接受
"eslint:recommended"
和"eslint:all"
字符串¥
"eslint:recommended"
and"eslint:all"
strings no longer accepted in flat config -
no-inner-declarations
有一个新的默认行为和一个新选项¥
no-inner-declarations
has a new default behavior with a new option -
no-useless-computed-key
默认情况下标记类中不必要的计算成员名称¥
no-useless-computed-key
flags unnecessary computed member names in classes by default
对插件开发者的重大更改
¥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
删除了多个格式化程序
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-jsdoc
和 valid-jsdoc
规则
¥ Removed require-jsdoc
and valid-jsdoc
rules
require-jsdoc
和 valid-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.
¥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 eslint
或eslint
(如果全局安装),ESLint 会假设你想要对当前目录进行 lint 检测。实际上,不通过任何模式相当于通过.
。¥Flat config. If you are using flat config, you can run
npx eslint
oreslint
(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
现在不允许对同一规则有多个 /* eslint */
注释
¥ Multiple /* eslint */
comments for the same rule are now disallowed
在 ESLint v9.0.0 之前,如果被检查的文件包含同一规则的多个 /* eslint */
配置注释,则将应用最后一个,而其他的将被默默忽略。例如:
¥Prior to ESLint v9.0.0, if the file being linted contained multiple /* eslint */
configuration comments for the same rule, the last one would be applied, while the others would be silently ignored. For example:
/* eslint semi: ["error", "always"] */
/* eslint semi: ["error", "never"] */
foo() // valid, because the configuration is "never"
在 ESLint v9.0.0 中,应用第一个,而其他则报告为 lint 错误:
¥In ESLint v9.0.0, the first one is applied, while the others are reported as lint errors:
/* eslint semi: ["error", "always"] */
/* eslint semi: ["error", "never"] */ // error: Rule "semi" is already configured by another configuration comment in the preceding code. This configuration is ignored.
foo() // error: Missing semicolon
要解决:删除重复的 /* eslint */
注释。
¥To address: Remove duplicate /* eslint */
comments.
相关问题):#18132
¥Related issue(s): #18132
更严格的 /* 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 */
本例中的 true
和 false
对 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-return
和 no-sequences
规则模式更严格
¥ no-constructor-return
and no-sequences
rule schemas are stricter
在 ESLint 的早期版本中,no-constructor-return
和 no-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-vars
的 varsIgnorePattern
选项错误地忽略了 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 function
s 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 function
s 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
camelcase
允许选项仅接受字符串数组
¥ camelcase
allow option only accepts an array of strings
以前,驼峰规则不强制 allow
选项为字符串数组。在 ESLint v9.0.0 中,allow
选项现在只接受字符串数组。
¥Previously the camelcase rule didn’t enforce the allow
option to be an array of strings. In ESLint v9.0.0, the allow
option now only accepts an array of strings.
要解决:如果 ESLint 报告此规则的配置无效,请更新你的配置。
¥To address: If ESLint reports invalid configuration for this rule, update your configuration.
相关问题):#18232
¥Related issue(s): #18232
删除了多个 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: Use the automated upgrade tool as recommended in the blog post.
¥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
代码路径现在已预先计算
¥ Code paths are now precalculated
在 ESLint v9.0.0 之前,代码路径是在规则使用的相同 AST 遍历期间计算的,这意味着传递给 onCodePathStart
和 onCodePathSegmentStart
等方法的信息是不完整的。具体来说,像 CodePath#childCodePaths
和 CodePathSegment#nextSegments
这样的数组属性一开始是空的,然后在遍历完成时填充适当的信息,这意味着这些数组可能具有不同的元素,具体取决于你检查其值的时间。
¥Prior to ESLint v9.0.0, code paths were calculated during the same AST traversal used by rules, meaning that the information passed to methods like onCodePathStart
and onCodePathSegmentStart
was incomplete. Specifically, array properties like CodePath#childCodePaths
and CodePathSegment#nextSegments
began empty and then were filled with the appropriate information as the traversal completed, meaning that those arrays could have different elements depending on when you checked their values.
ESLint v9.0.0 现在在规则使用的遍历之前预先计算代码路径信息。因此,无论在规则内部的何处访问代码路径信息,现在都是完整的。
¥ESLint v9.0.0 now precalculates code path information before the traversal used by rules. As a result, the code path information is now complete regardless of where it is accessed inside of a rule.
要解决:如果你要访问 CodePath
或 CodePathSegment
上的任何数组属性,则需要更新代码。具体来说:
¥To address: If you are accessing any array properties on CodePath
or CodePathSegment
, you’ll need to update your code. Specifically:
-
如果你要检查任何数组属性的
length
,请确保使用相对比较运算符,例如<
、>
、<=
和>=
,而不是等于。¥If you are checking the
length
of any array properties, ensure you are using relative comparison operators like<
,>
,<=
, and>=
instead of equals. -
如果你要访问
CodePathSegment
或CodePath#childCodePaths
上的nextSegments
、prevSegments
、allNextSegments
或allPrevSegments
属性,请验证你的代码是否仍能按预期工作。为了向后兼容,请考虑将检查这些属性的逻辑移至onCodePathEnd
。¥If you are accessing the
nextSegments
,prevSegments
,allNextSegments
, orallPrevSegments
properties on aCodePathSegment
, orCodePath#childCodePaths
, verify that your code will still work as expected. To be backwards compatible, consider moving the logic that checks these properties intoonCodePathEnd
.
相关问题:#16999
¥Related Issues(s): #16999
不再支持函数式规则
¥ 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.
要解决:将你的规则更新为 最新的规则格式。对于用 CommonJS 编写的规则,你也可以使用 eslint-transforms
。
¥To address: Update your rules to the most recent rule format. For rules written in CommonJS, you can also use eslint-transforms
.
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
tofalse
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:
-
请注意
ecmaVersion
和sourceType
的新默认值。默认情况下,RuleTester
使用ecmaVersion: "latest"
和sourceType: "module"
的扁平配置默认值。如果某些测试期望使用旧的默认值ecmaVersion: 5
和sourceType: "script"
,这可能会导致某些测试失败。如果你想使用旧的默认值,则需要在RuleTester
中手动指定,如下所示:¥Be aware of new defaults for
ecmaVersion
andsourceType
. By default,RuleTester
uses the flat config default ofecmaVersion: "latest"
andsourceType: "module"
. This may cause some tests to break if they were expecting the old default ofecmaVersion: 5
andsourceType: "script"
. If you’d like to use the old default, you’ll need to manually specify that in yourRuleTester
like this:// use eslintrc defaults const ruleTester = new RuleTester({ languageOptions: { ecmaVersion: 5, sourceType: "script" } });
-
将
parserOptions
更改为languageOptions
。如果你在测试中设置ecmaVersion
或sourceType
,请将它们从parserOptions
移至languageOptions
,如下所示:¥Change
parserOptions
tolanguageOptions
. If you’re settingecmaVersion
orsourceType
on your tests, move those fromparserOptions
tolanguageOptions
, 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 配置系统上运行的
env
和parser
等键必须转换为扁平配置系统。有关转换你可能使用的其他按键的详细信息,请参阅 配置迁移指南。¥Translate other config keys. Keys such as
env
andparser
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
检查
为了帮助开发没有常见错误的高质量自定义规则,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
:
-
测试用例
output
必须与code
不同。在 ESLint v8.x 中,如果output
与code
相同,则断言没有自动修复。在查看测试用例时,并不总是立即清楚output
是否与code
不同,特别是当字符串较长或多行时,这使得开发者很难确定测试用例是否需要自动修复。在 ESLint v9.0.0 中,为了避免这种歧义,如果测试output
与测试code
具有相同的值,RuleTester
现在会抛出错误。因此,现在指定output
必然意味着测试用例需要自动修复并断言其结果。如果测试用例不需要自动修复,请忽略output
属性或将其设置为null
。这断言没有自动修复。¥Test case
output
must be different fromcode
. In ESLint v8.x, ifoutput
is the same ascode
, it asserts that there was no autofix. When looking at a test case, it’s not always immediately clear whetheroutput
differs fromcode
, 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 testoutput
has the same value as the testcode
. Therefore, specifyingoutput
now necessarily means that the test case expects an autofix and asserts its result. If the test case doesn’t expect an autofix, omit theoutput
property or set it tonull
. This asserts that there was no autofix. -
测试错误对象必须指定
message
或messageId
。为了提高测试覆盖率的质量,如果测试错误对象上既没有指定message
也没有指定messageId
,RuleTester
现在会引发错误。¥Test error objects must specify
message
ormessageId
. To improve the quality of test coverage,RuleTester
now throws an error if neithermessage
normessageId
is specified on test error objects. -
如果实际错误提供建议,测试错误对象必须指定
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 thesuggestions
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 thesuggestions
property asserts that the actual error does not provide suggestions, while you need to specify thesuggestions
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 specifysuggestions: <number>
to assert just the number of suggestions. -
测试建议对象必须指定
output
。为了提高测试覆盖率的质量,如果未在测试建议对象上指定output
属性,RuleTester
现在会引发错误。¥Test suggestion objects must specify
output
. To improve the quality of test coverage,RuleTester
now throws an error ifoutput
property is not specified on test suggestion objects. -
测试建议对象必须指定
desc
或messageId
。为了提高测试覆盖率的质量,如果测试建议对象上未指定desc
和messageId
属性,RuleTester
现在会引发错误。也不允许同时指定两者。如果除了messageId
之外你还想断言建议描述文本,那么还需要添加data
属性。¥Test suggestion objects must specify
desc
ormessageId
. To improve the quality of test coverage,RuleTester
now throws an error if neitherdesc
normessageId
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 themessageId
, then also add thedata
property. -
建议消息必须是唯一的。由于建议通常在编辑器中显示为下拉列表,因此针对同一 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.
-
建议必须修改代码。预计建议通过更改代码来解决报告的问题。如果建议测试
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 testoutput
is the same as the testcode
. -
建议必须生成有效的语法。为了使规则建议有用,它们必须是有效的语法。
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 thecode
value and throws an error if parsing fails. -
测试用例必须是唯一的。相同的测试用例可能会导致混乱,并且很难在长测试文件中手动检测到。现在可以自动检测重复项并安全删除。
¥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.
-
filename
和only
必须是预期的类型。RuleTester
现在检查测试对象的filename
和only
属性的类型。如果指定,filename
必须是字符串值。如果指定,only
必须是布尔值。¥**
filename
andonly
must be of the expected type.**RuleTester
now checks the type offilename
andonly
properties of test objects. If specified,filename
must be a string value. If specified,only
must be a boolean value. -
消息不能有未替换的占位符。
RuleTester
现在还会检查消息中是否仍有{{ placeholder }}
,因为它们的值未在相应的context.report()
调用中通过data
传递。¥Messages cannot have unsubstituted placeholders. The
RuleTester
now also checks if there are{{ placeholder }}
still in the message as their values were not passed viadata
in the respectivecontext.report()
call.
要解决:使用 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, #18016
¥Related Issues(s): #15104, #15735, #16908, #18016
FlatESLint
现在是 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