配置文件
你可以将 ESLint 项目配置放在配置文件中。你可以包含内置规则、你希望如何执行这些规则、带有自定义规则的插件、可共享的配置、以及你希望规则适用的文件等内容。
🌐 You can put your ESLint project configuration in a configuration file. You can include built-in rules, how you want them enforced, plugins with custom rules, shareable configurations, which files you want rules to apply to, and more.
配置文件
🌐 Configuration File
ESLint 配置文件可以命名为以下任意名称:
🌐 The ESLint configuration file may be named any of the following:
eslint.config.jseslint.config.mjseslint.config.cjseslint.config.ts(需要额外设置)eslint.config.mts(需要额外设置)eslint.config.cts(需要额外设置)
它应该放置在你项目的根目录中,并导出一个 配置对象 数组。以下是一个示例:
🌐 It should be placed in the root directory of your project and export an array of configuration objects. Here’s an example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
rules: {
semi: "error",
"prefer-const": "error",
},
},
]);
在此示例中,defineConfig() 辅助工具用于定义一个仅包含一个配置对象的配置数组。该配置对象启用了两条规则:semi 和 prefer-const。这些规则适用于使用该配置文件的所有 ESLint 处理的文件。
🌐 In this example, the defineConfig() helper is used to define a configuration array with just one configuration object. The configuration object enables two rules: semi and prefer-const. These rules are applied to all of the files ESLint processes using this config file.
如果你的项目在其 package.json 文件中未指定 "type":"module",那么 eslint.config.js 必须采用 CommonJS 格式,例如:
🌐 If your project does not specify "type":"module" in its package.json file, then eslint.config.js must be in CommonJS format, such as:
// eslint.config.js
const { defineConfig } = require("eslint/config");
module.exports = defineConfig([
{
rules: {
semi: "error",
"prefer-const": "error",
},
},
]);
配置对象
🌐 Configuration Objects
每个配置对象包含 ESLint 执行一组文件所需的所有信息。每个配置对象由以下属性组成:
🌐 Each configuration object contains all of the information ESLint needs to execute on a set of files. Each configuration object is made up of these properties:
name- 配置对象的名称。这用于错误消息和配置检查器,以帮助识别正在使用的配置对象。(命名约定)basePath- 一个字符串,指定配置对象应应用到的子目录的路径。它可以是相对路径或绝对路径。files- 一个包含全局模式的数组,指示配置对象应适用于的文件。如果未指定,配置对象将适用于任何其他配置对象匹配的所有文件。ignores- 一个全局模式数组,指示配置对象不应应用到的文件。如果未指定,则配置对象适用于所有与files匹配的文件。如果在配置对象中仅使用ignores而没有其他键,则这些模式作为全局忽略起作用,并且它将应用于每个配置对象。extends- 包含要应用的其他配置的字符串、配置对象或配置数组的数组。language- 一个字符串,指定用于 lint 的语言,格式为"pluginName/languageName",例如"markdown/commonmark"。(默认值:JavaScript 的"js/js")languageOptions- 一个包含与指定语言的代码规范检查配置相关的设置的对象。对于 JavaScript,这些设置为:ecmaVersion- 要支持的 ECMAScript 版本。可以是任意年份(例如,2022)或版本(例如,5)。设置为"latest"以使用最新支持的版本。(默认:"latest")sourceType- JavaScript 源代码的类型。可能的值为"script"表示传统脚本文件,"module"表示 ECMAScript 模块(ESM),以及"commonjs"表示 CommonJS 文件。(默认值:"module"适用于.js和.mjs文件;"commonjs"适用于.cjs文件)globals- 指定在代码检查期间应添加到全局作用域的其他对象的对象。parser- 一个包含parse()方法或parseForESLint()方法的对象。(默认值:espree)parserOptions- 一个对象,指定额外的选项,这些选项会直接传递给解析器上的parse()或parseForESLint()方法。可用的选项取决于解析器。
linterOptions- 包含与代码检查过程相关的设置的对象。noInlineConfig- 一个布尔值,指示是否允许内联配置。reportUnusedDisableDirectives- 一个严重性字符串,用于指示是否以及如何跟踪和报告未使用的禁用和启用指令。为了兼容旧版本,true等同于"warn",false等同于"off"。(默认值:"warn")。reportUnusedInlineConfigs- 一个严重性字符串,用于指示是否以及如何跟踪和报告未使用的内联配置。(默认值:"off")
processor- 要么是一个包含preprocess()和postprocess()方法的对象,要么是一个表示插件内部处理器名称的字符串(例如,"pluginName/processorName")。plugins- 一个包含插件名称到插件对象的名称-值映射的对象。当指定files时,这些插件仅对匹配的文件可用。rules- 一个包含已配置规则的对象。当指定files或ignores时,这些规则配置仅适用于匹配的文件。settings- 一个包含名称-值对信息的对象,所有规则都应使用这些信息。
指定 files 和 ignores
🌐 Specify files and ignores
你可以使用 files 和 ignores 的组合来确定配置对象应应用于哪些文件以及哪些文件不应用。以下是一个示例:
🌐 You can use a combination of files and ignores to determine which files the configuration object should apply to and which not. Here’s an example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
// matches all files ending with .js
{
files: ["**/*.js"],
rules: {
semi: "error",
},
},
// matches all files ending with .js except those in __tests
{
files: ["**/*.js"],
ignores: ["__tests/**"],
rules: {
"no-console": "error",
},
},
]);
没有 files 或 ignores 的配置对象会自动应用到任何被其他配置对象匹配的文件。例如:
🌐 Configuration objects without files or ignores are automatically applied to any file that is matched by any other configuration object. For example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
// matches all files because it doesn't specify the `files` or `ignores` key
{
rules: {
semi: "error",
},
},
]);
在此配置下,semi 规则会针对所有符合 ESLint 默认文件的文件启用。因此,如果你向 ESLint 传递 example.js,则会应用 semi 规则。如果你传递一个非 JavaScript 文件,例如 example.txt,则不会应用 semi 规则,因为没有其他配置对象与该文件名匹配。(ESLint 会输出一条错误信息,告诉你该文件因缺少配置而被忽略。)
🌐 With this configuration, the semi rule is enabled for all files that match the default files in ESLint. So if you pass example.js to ESLint, the semi rule is applied. If you pass a non-JavaScript file, like example.txt, the semi rule is not applied because there are no other configuration objects that match that filename. (ESLint outputs an error message letting you know that the file was ignored due to missing configuration.)
指定具有任意扩展名的文件
🌐 Specify files with arbitrary extensions
要对默认的 .js、.cjs 和 .mjs 以外的扩展名的文件进行 lint,需要将它们包含在 files 中,并使用 "**/*.extension" 格式的模式。任何模式都可以使用,但如果模式是 * 或以 /* 或 /** 结尾则除外。
例如,要对扩展名为 .ts、.cts 和 .mts 的 TypeScript 文件进行 lint,可以指定如下配置对象:
🌐 To lint files with extensions other than the default .js, .cjs and .mjs, include them in files with a pattern in the format of "**/*.extension". Any pattern will work except if it is * or if it ends with /* or /**.
For example, to lint TypeScript files with .ts, .cts and .mts extensions, you would specify a configuration object like this:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.ts", "**/*.cts", "**/*.mts"],
},
// ...other config
]);
指定无扩展名的文件
🌐 Specify files without extension
没有扩展名的文件可以与模式 !(*.*) 匹配。例如:
🌐 Files without an extension can be matched with the pattern !(*.*). For example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/!(*.*)"],
},
// ...other config
]);
上述配置会对所有目录中除了默认 .js、.cjs 和 .mjs 扩展名之外的无扩展名文件进行检查。
🌐 The above config lints files without extension besides the default .js, .cjs and .mjs extensions in all directories.
使用 AND 操作指定文件
🌐 Specify files with an AND operation
可以通过在 files 数组中使用字符串数组,对同一个文件匹配多个模式。例如:
🌐 Multiple patterns can be matched against the same file by using an array of strings inside of the files array. For example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: [["src/*", "**/.js"]],
},
// ...other config
]);
当一个文件既在 src 目录中又以 .js 结尾时,模式 ["src/*", "**/.js"] 会匹配它。当你动态计算 files 数组的值并且想要通过将多个全局匹配模式合并到一个字符串中来避免潜在错误时,这种方法会很有帮助。
🌐 The pattern ["src/*", "**/.js"] matches when a file is both inside of the src directory and also ends with .js. This approach can be helpful when you’re dynamically calculating the value of the files array and want to avoid potential errors by trying to combine multiple glob patterns into a single string.
排除包含 ignores 的文件
🌐 Exclude files with ignores
你可以通过指定 files 和 ignores 模式的组合来限制配置对象适用的文件。例如,你可能希望某些规则仅适用于 src 目录中的文件:
🌐 You can limit which files a configuration object applies to by specifying a combination of files and ignores patterns. For example, you may want certain rules to apply only to files in your src directory:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["src/**/*.js"],
rules: {
semi: "error",
},
},
]);
在这里,只有 src 目录下的 JavaScript 文件应用了 semi 规则。如果你对另一个目录中的文件运行 ESLint,这个配置对象将被跳过。通过添加 ignores,你还可以从这个配置对象中移除 src 中的一些文件:
🌐 Here, only the JavaScript files in the src directory have the semi rule applied. If you run ESLint on files in another directory, this configuration object is skipped. By adding ignores, you can also remove some of the files in src from this configuration object:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["src/**/*.js"],
ignores: ["**/*.config.js"],
rules: {
semi: "error",
},
},
]);
此配置对象匹配 src 目录中的所有 JavaScript 文件,但不包括以 .config.js 结尾的文件。你还可以在 ignores 中使用否定模式来从忽略模式中排除文件,例如:
🌐 This configuration object matches all JavaScript files in the src directory except those that end with .config.js. You can also use negation patterns in ignores to exclude files from the ignore patterns, such as:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["src/**/*.js"],
ignores: ["**/*.config.js", "!**/eslint.config.js"],
rules: {
semi: "error",
},
},
]);
在这里,配置对象排除了以 .config.js 结尾的文件,但不包括 eslint.config.js。该文件仍然应用了 semi。
🌐 Here, the configuration object excludes files ending with .config.js except for eslint.config.js. That file still has semi applied.
非全局的 ignores 模式只能匹配文件名。像 "dir-to-exclude/" 这样的模式不会忽略任何内容。要忽略特定目录中的所有内容,应该使用像 "dir-to-exclude/**" 这样的模式。
🌐 Non-global ignores patterns can only match file names. A pattern like "dir-to-exclude/" will not ignore anything. To ignore everything in a particular directory, a pattern like "dir-to-exclude/**" should be used instead.
如果在没有 files 的情况下使用 ignores,并且存在其他键(例如 rules),那么配置对象将适用于所有已进行 lint 的文件,除了被 ignores 排除的文件,例如:
🌐 If ignores is used without files and there are other keys (such as rules), then the configuration object applies to all linted files except the ones excluded by ignores, for example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
ignores: ["**/*.config.js"],
rules: {
semi: "error",
},
},
]);
此配置对象适用于所有 JavaScript 文件,除了以 .config.js 结尾的文件。实际上,这就像将 files 设置为 **/*。一般来说,如果你指定了 ignores,通常最好总是包含 files。
🌐 This configuration object applies to all JavaScript files except those ending with .config.js. Effectively, this is like having files set to **/*. In general, it’s a good idea to always include files if you are specifying ignores.
请注意,当未指定 files 时,被否定的 ignores 模式不会导致任何匹配的文件被自动进行 lint。ESLint 只会 lint 默认匹配的文件,或者匹配 files 模式(且该模式不是 * 并且不以 /* 或 /** 结尾)的文件。
🌐 Note that when files is not specified, negated ignores patterns do not cause any matching files to be linted automatically.
ESLint only lints files that are matched either by default or by a files pattern that is not * and does not end with /* or /**.
在全球范围内忽略包含 ignores 的文件
🌐 Globally ignore files with ignores
根据 ignores 属性的使用方式,它可以表现为非全局的 ignores 或全局的 ignores。
🌐 Depending on how the ignores property is used, it can behave as non-global ignores or as global ignores.
- 当在配置对象中仅使用
ignores(除了name之外没有其他键)时,这些模式会作为全局忽略。这意味着它们适用于每一个配置对象(而不仅仅是定义它的配置对象)。全局ignores允许你无需在多个配置对象中复制并保持ignores属性同步。 - 如果
ignores与同一配置对象中的其他属性一起使用,则这些模式将作为非全局忽略。这样,ignores只应用于其定义的配置对象。
全局和非全局 ignores 在使用上有一些差异:
🌐 Global and non-global ignores have some usage differences:
- 在非全局
ignores中的模式仅匹配文件 (dir/filename.js) 或目录中的文件 (dir/**) - 全局
ignores中的模式除了非全局忽略支持的模式之外,还可以匹配目录(dir/)。
对于所有 ignores 的使用情况:
🌐 For all uses of ignores:
- 你定义的模式会被添加到默认的 ESLint 模式之后,默认模式是
["**/node_modules/", ".git/"]。 - 这些模式总是匹配以点开头的文件和目录,例如
.foo.js或.fixtures,除非这些文件被明确忽略。默认情况下唯一被忽略的点目录是.git。
// eslint.config.js
import { defineConfig } from "eslint/config";
// Example of global ignores
export default defineConfig([
{
ignores: [".config/", "dist/", "tsconfig.json"] // acts as global ignores, due to the absence of other properties
},
{ ... }, // ... other configuration object, inherit global ignores
{ ... }, // ... other configuration object, inherit global ignores
]);
// Example of non-global ignores
export default defineConfig([
{
ignores: [".config/**", "dir1/script1.js"],
rules: { ... } // the presence of this property dictates non-global ignores
},
{
ignores: ["other-dir/**", "dist/script2.js"],
rules: { ... } // the presence of this property dictates non-global ignores
},
]);
为了避免混淆,使用 globalIgnores() 辅助函数来明确表示哪些忽略是全局的。下面是之前的示例,重写为使用 globalIgnores():
🌐 To avoid confusion, use the globalIgnores() helper function to clearly indicate which ignores are meant to be global. Here’s the previous example rewritten to use globalIgnores():
// eslint.config.js
import { defineConfig, globalIgnores } from "eslint/config";
// Example of global ignores
export default defineConfig([
globalIgnores([".config/", "dist/", "tsconfig.json"]),
{ ... }, // ... other configuration object, inherit global ignores
{ ... }, // ... other configuration object, inherit global ignores
]);
// Example of non-global ignores
export default defineConfig([
{
ignores: [".config/**", "dir1/script1.js"],
rules: { ... } // the presence of this property dictates non-global ignores
},
{
ignores: ["other-dir/**", "dist/script2.js"],
rules: { ... } // the presence of this property dictates non-global ignores
},
]);
有关配置 ignores 规则的更多信息和示例,请参见 忽略文件。
🌐 For more information and examples on configuring rules regarding ignores, see Ignore Files.
指定基础路径
🌐 Specify base path
你可以选择指定 basePath,将配置对象应用于特定的子目录(包括其子目录)。
🌐 You can optionally specify basePath to apply the configuration object to a specific subdirectory (including its subdirectories).
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
// matches all files in tests and its subdirectories
{
basePath: "tests",
rules: {
"no-undef": "error",
},
},
// matches all files ending with spec.js in tests and its subdirectories
{
basePath: "tests",
files: ["**/*.spec.js"],
languageOptions: {
globals: {
it: "readonly",
describe: "readonly",
},
},
},
// globally ignores tests/fixtures directory
{
basePath: "tests",
ignores: ["fixtures/"],
},
]);
结合 extends,可以通过只指定一次 basePath 将多个配置对象应用于同一子目录,如下所示:
🌐 In combination with extends, multiple configuration objects can be applied to the same subdirectory by specifying basePath only once, like this:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
basePath: "tests",
extends: [
// matches all files in tests and its subdirectories
{
rules: {
"no-undef": "error",
},
},
// matches all files ending with spec.js in tests and its subdirectories
{
files: ["**/*.spec.js"],
languageOptions: {
globals: {
it: "readonly",
describe: "readonly",
},
},
},
// globally ignores tests/fixtures directory
{
ignores: ["fixtures/"],
},
],
},
]);
级联配置对象
🌐 Cascading Configuration Objects
当多个配置对象匹配给定的文件名时,这些配置对象会被合并,在出现冲突时,后面的对象会覆盖前面的对象。例如:
🌐 When more than one configuration object matches a given filename, the configuration objects are merged with later objects overriding previous objects when there is a conflict. For example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
languageOptions: {
globals: {
MY_CUSTOM_GLOBAL: "readonly",
},
},
},
{
files: ["tests/**/*.js"],
languageOptions: {
globals: {
it: "readonly",
describe: "readonly",
},
},
},
]);
使用此配置,所有 JavaScript 文件都会定义一个名为 MY_CUSTOM_GLOBAL 的自定义全局对象,而 tests 目录中的那些 JavaScript 文件除了 MY_CUSTOM_GLOBAL 外,还定义了 it 和 describe 作为全局对象。对于 tests 目录中的任何 JavaScript 文件,这两个配置对象都会被应用,因此 languageOptions.globals 会合并以创建最终结果。
🌐 Using this configuration, all JavaScript files define a custom global object defined called MY_CUSTOM_GLOBAL while those JavaScript files in the tests directory have it and describe defined as global objects in addition to MY_CUSTOM_GLOBAL. For any JavaScript file in the tests directory, both configuration objects are applied, so languageOptions.globals are merged to create a final result.
配置 Linter 选项
🌐 Configure Linter Options
可以使用 linterOptions 对象配置特定于代码检查过程的选项。这些选项会影响代码检查的执行方式,但不会影响文件源代码的解释方式。
🌐 Options specific to the linting process can be configured using the linterOptions object. These effect how linting proceeds and does not affect how the source code of the file is interpreted.
禁用内联配置
🌐 Disable Inline Configuration
内联配置是使用 /*eslint*/ 注释实现的,例如 /*eslint semi: error*/。你可以通过将 noInlineConfig 设置为 true 来禁止内联配置。启用后,所有内联配置将被忽略。以下是一个示例:
🌐 Inline configuration is implemented using an /*eslint*/ comment, such as /*eslint semi: error*/. You can disallow inline configuration by setting noInlineConfig to true. When enabled, all inline configuration is ignored. Here’s an example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
linterOptions: {
noInlineConfig: true,
},
},
]);
报告未使用的禁用指令
🌐 Report Unused Disable Directives
禁用和启用指令,例如 /*eslint-disable*/、/*eslint-enable*/ 和 /*eslint-disable-next-line*/,用于在代码的某些部分禁用 ESLint 规则。随着代码的变化,这些指令可能不再需要,因为代码已经发生了变化,导致规则不再被触发。你可以通过将 reportUnusedDisableDirectives 选项设置为严重性字符串来启用对这些未使用的禁用指令的报告,如下例所示:
🌐 Disable and enable directives such as /*eslint-disable*/, /*eslint-enable*/ and /*eslint-disable-next-line*/ are used to disable ESLint rules around certain portions of code. As code changes, it’s possible for these directives to no longer be needed because the code has changed in such a way that the rule is no longer triggered. You can enable reporting of these unused disable directives by setting the reportUnusedDisableDirectives option to a severity string, as in this example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
linterOptions: {
reportUnusedDisableDirectives: "error",
},
},
]);
此设置默认值为 "warn"。
🌐 This setting defaults to "warn".
你可以使用 --report-unused-disable-directives 或 --report-unused-disable-directives-severity 命令行选项来覆盖此设置。
🌐 You can override this setting using the --report-unused-disable-directives or the --report-unused-disable-directives-severity command line options.
为了兼容旧版,true 等同于 "warn",false 等同于 "off"。
🌐 For legacy compatibility, true is equivalent to "warn" and false is equivalent to "off".
报告未使用的内联配置
🌐 Report Unused Inline Configs
内联配置注释,例如 /* eslint rule-name: "error" */,用于更改特定代码部分的 ESLint 规则严重性和/或选项。随着项目的 ESLint 配置文件发生变化,这些指令可能不再与已设置的内容不同。你可以通过将 reportUnusedInlineConfigs 选项设置为严重性字符串来启用对这些未使用的内联配置注释的报告,如以下示例所示:
🌐 Inline config comments such as /* eslint rule-name: "error" */ are used to change ESLint rule severity and/or options around certain portions of code.
As a project’s ESLint configuration file changes, it’s possible for these directives to no longer be different from what was already set.
You can enable reporting of these unused inline config comments by setting the reportUnusedInlineConfigs option to a severity string, as in this example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
linterOptions: {
reportUnusedInlineConfigs: "error",
},
},
]);
你可以使用 --report-unused-inline-configs 命令行选项覆盖此设置。
🌐 You can override this setting using the --report-unused-inline-configs command line option.
配置规则
🌐 Configure Rules
你可以通过在配置对象中添加一个包含规则配置的 rules 属性来配置任意数量的规则。该对象中的名称是规则的名称,值是每个规则的配置。示例如下:
🌐 You can configure any number of rules in a configuration object by adding a rules property containing an object with your rule configurations. The names in this object are the names of the rules and the values are the configurations for each of those rules. Here’s an example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
rules: {
semi: "error",
},
},
]);
此配置对象指定 semi 规则应启用,严重性为 "error"。你还可以通过指定数组为规则提供选项,其中第一个项目是严重性,之后的每个项目都是规则的选项。例如,你可以通过传递 "never" 作为选项,将 semi 规则切换为不允许分号:
🌐 This configuration object specifies that the semi rule should be enabled with a severity of "error". You can also provide options to a rule by specifying an array where the first item is the severity and each item after that is an option for the rule. For example, you can switch the semi rule to disallow semicolons by passing "never" as an option:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
rules: {
semi: ["error", "never"],
},
},
]);
每条规则都指定自己的选项,并且可以是任何有效的 JSON 数据类型。请查阅你要配置的规则的文档,以获取有关其可用选项的更多信息。
🌐 Each rule specifies its own options and can be any valid JSON data type. Please check the documentation for the rule you want to configure for more information about its available options.
有关配置规则的更多信息,请参阅 配置规则。
🌐 For more information on configuring rules, see Configure Rules.
配置共享设置
🌐 Configure Shared Settings
ESLint 支持将共享设置添加到配置文件中。当你将一个 settings 对象添加到配置对象时,它会提供给每一条规则。按照惯例,插件会为它们关心的设置使用命名空间,以避免与其他设置冲突。插件可以使用 settings 来指定应在其所有规则中共享的信息。如果你正在添加自定义规则并希望它们能够访问相同的信息,这可能会很有用。下面是一个示例:
🌐 ESLint supports adding shared settings into configuration files. When you add a settings object to a configuration object, it is supplied to every rule. By convention, plugins namespace the settings they are interested in to avoid collisions with others. Plugins can use settings to specify the information that should be shared across all of their rules. This may be useful if you are adding custom rules and want them to have access to the same information. Here’s an example:
// eslint.config.js
import { defineConfig } from "eslint/config";
export default defineConfig([
{
settings: {
sharedData: "Hello",
},
plugins: {
customPlugin: {
rules: {
"my-rule": {
meta: {
// custom rule's meta information
},
create(context) {
const sharedData = context.settings.sharedData;
return {
// code
};
},
},
},
},
},
rules: {
"customPlugin/my-rule": "error",
},
},
]);
扩展配置
🌐 Extending Configurations
一个配置对象使用 extends 来继承另一个配置对象或数组的所有特性(包括规则、插件和语言选项),然后可以修改所有选项。extends 键是一个值数组,指示要从哪些配置扩展。extends 数组的元素可以是以下三种值之一:
🌐 A configuration object uses extends to inherit all the traits of another configuration object or array (including rules, plugins, and language options) and can then modify all the options. The extends key is an array of values indicating which configurations to extend from. The elements of the extends array can be one of three values:
- 指定插件中配置名称的字符串
- 配置对象
- 配置数组
使用插件的配置
🌐 Use Configurations from Plugins
ESLint 插件可以导出预定义的配置。这些配置可以通过字符串引用,并遵循 pluginName/configName 模式。插件必须首先在 plugins 键中指定。示例如下:
🌐 ESLint plugins can export predefined configurations. These configurations are referenced using a string and follow the pattern pluginName/configName. The plugin must be specified in the plugins key first. Here’s an example:
// eslint.config.js
import examplePlugin from "eslint-plugin-example";
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
plugins: {
example: examplePlugin,
},
extends: ["example/recommended"],
},
]);
在此示例中,从 eslint-plugin-example 加载名为 recommended 的配置。插件配置也可以在配置数组中通过名称引用。
🌐 In this example, the configuration named recommended from eslint-plugin-example is loaded. The plugin configurations can also be referenced by name inside of the configuration array.
你也可以将插件配置直接插入到 extends 数组中。例如:
🌐 You can also insert plugin configurations directly into the extends array. For example:
// eslint.config.js
import pluginExample from "eslint-plugin-example";
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
plugins: {
example: pluginExample,
},
extends: [pluginExample.configs.recommended],
},
]);
在这种情况下,可以通过插件对象的 configs 属性直接访问来自 eslint-plugin-example 的名为 recommended 的配置。
🌐 In this case, the configuration named recommended from eslint-plugin-example is accessed directly through the plugin object’s configs property.
使用预定义配置
🌐 Use Predefined Configurations
ESLint 有两个预定义的 JavaScript 配置:
🌐 ESLint has two predefined configurations for JavaScript:
js/recommended- 启用 ESLint 建议每个人都使用的规则以避免潜在错误。js/all- 启用 ESLint 自带的所有规则。由于该配置会随着 ESLint 的每个小版本和大版本而改变,因此不推荐在生产环境中使用。请自行承担风险。
要包含这些预定义配置,请安装 @eslint/js 包,然后在后续的配置对象中对其他属性进行任何修改:
🌐 To include these predefined configurations, install the @eslint/js package and then make any modifications to other properties in subsequent configuration objects:
// eslint.config.js
import js from "@eslint/js";
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
plugins: {
js,
},
extends: ["js/recommended"],
rules: {
"no-unused-vars": "warn",
},
},
]);
在这里,首先应用 js/recommended 预定义配置,然后另一个配置对象为 no-unused-vars 添加所需的配置。
🌐 Here, the js/recommended predefined configuration is applied first and then another configuration object adds the desired configuration for no-unused-vars.
有关如何将预定义配置与你的偏好相结合的更多信息,请参见 Combine Configs。
🌐 For more information on how to combine predefined configs with your preferences, please see Combine Configs.
使用可共享的配置包
🌐 Use a Shareable Configuration Package
可共享的配置是一个导出配置对象或数组的 npm 包。该包应作为依赖安装在你的项目中,然后从你的 eslint.config.js 文件中引用。例如,要使用名为 eslint-config-example 的可共享配置,你的配置文件如下所示:
🌐 A sharable configuration is an npm package that exports a configuration object or array. This package should be installed as a dependency in your project and then referenced from inside of your eslint.config.js file. For example, to use a shareable configuration named eslint-config-example, your configuration file would look like this:
// eslint.config.js
import exampleConfig from "eslint-config-example";
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.js"],
extends: [exampleConfig],
rules: {
"no-unused-vars": "warn",
},
},
]);
在这个例子中,exampleConfig 可以是一个对象或一个数组,无论哪种情况,它都可以直接插入到 extends 数组中。
🌐 In this example, exampleConfig can be either an object or an array, and either way it can be inserted directly into the extends array.
有关如何将可共享的配置与你的偏好结合的更多信息,请参见 Combine Configs。
🌐 For more information on how to combine shareable configs with your preferences, please see Combine Configs.
何时使用扩展规则 (Extends) 与级联规则 (Cascading)
🌐 When to Use Extends vs Cascading
何时使用 Extends:
🌐 When to use Extends:
- 用于重用配置 - 当你想继承并基于现有的插件配置、可共享的包或预定义配置进行构建时。
- 用于插件配置 - 当应用来自 ESLint 插件(例如
example/recommended)的推荐或特定配置时。 - 用于可共享配置 - 当使用导出配置对象的 npm 包(例如
eslint-config-example)时。 - 对于预定义配置 - 使用 ESLint 内置配置如
js/recommended或js/all时。 - 用于模块化配置 - 当你想将多个配置源组合成一个配置对象时。
- 为了保持一致性 - 当你希望在多个配置对象中确保一致的基本规则时。
- 用于插件集成 - 当你需要应用随插件打包的配置时。
何时使用 Cascading:
🌐 When to use Cascading:
- 针对特定文件的规则 - 当你需要针对不同的文件模式或目录制定不同规则时。
- 用于渐进式配置 - 当你想将基础规则应用于所有文件,然后为特定子集添加/覆盖规则时。
- 针对特定环境的设置 - 当测试文件、源文件和配置文件需要不同的规则集时。
- 用于基于目录的配置 - 当不同的项目目录需要不同的代码检查方式时。
- 用于规则严重性调整 - 当你想要更改特定文件模式的规则严重性(
error/warn/off)时。 - 用于语言选项的变化 - 当不同的文件需要不同的 ECMAScript 版本或解析器选项时。
配置命名约定
🌐 Configuration Naming Conventions
name 属性是可选的,但建议为每个配置对象提供一个名称,特别是在创建共享配置时。名称用于错误信息和配置检查器中,以帮助识别正在使用的配置对象。
🌐 The name property is optional, but it is recommended to provide a name for each configuration object, especially when you are creating shared configurations. The name is used in error messages and the config inspector to help identify which configuration object is being used.
名称应描述配置对象的用途,并使用 / 作为分隔符,与配置名称或插件名称进行作用域限定。ESLint 并不强制在运行时名称必须唯一,但建议设置唯一名称以避免混淆。
🌐 The name should be descriptive of the configuration object’s purpose and scoped with the configuration name or plugin name using / as a separator. ESLint does not enforce the names to be unique at runtime, but it is recommended that unique names be set to avoid confusion.
例如,如果你正在为名为 eslint-plugin-example 的插件创建配置对象,你可以将 name 添加到带有 example/ 前缀的配置对象中:
🌐 For example, if you are creating a configuration object for a plugin named eslint-plugin-example, you might add name to the configuration objects with the example/ prefix:
export default {
configs: {
recommended: {
name: "example/recommended",
rules: {
"no-unused-vars": "warn",
},
},
strict: {
name: "example/strict",
rules: {
"no-unused-vars": "error",
},
},
},
};
在暴露配置对象数组时,name 可能有额外的作用域层级来帮助识别配置对象。例如:
🌐 When exposing arrays of configuration objects, the name may have extra scoping levels to help identify the configuration object. For example:
export default {
configs: {
strict: [
{
name: "example/strict/language-setup",
languageOptions: {
ecmaVersion: 2024,
},
},
{
name: "example/strict/sub-config",
files: ["src/**/*.js"],
rules: {
"no-unused-vars": "error",
},
},
],
},
};
配置文件解析
🌐 Configuration File Resolution
当在命令行上运行 ESLint 时,它会通过首先查看包含文件的目录,然后向上搜索祖级目录,直到找到 eslint.config.* 文件,为每个目标文件确定配置。这种行为提高了对 monorepos 的支持,其中子目录可以有自己的配置文件。
🌐 When ESLint is run on the command line, it determines configuration for each target file by first looking in the directory that contains the file and then searching up ancestor directories until it finds an eslint.config.* file. This behavior improves support for monorepos, where subdirectories can have their own configuration files.
你可以通过在命令行上使用 -c 或 --config 选项来指定备用配置文件,从而防止此搜索,例如:
🌐 You can prevent this search by using the -c or --config option on the command line to specify an alternate configuration file, such as:
npm
npx eslint --config some-other-file.js **/*.js
yarn
yarn dlx eslint --config some-other-file.js **/*.js
pnpm
pnpm dlx eslint --config some-other-file.js **/*.js
bun
bunx eslint --config some-other-file.js **/*.js
在这种情况下,ESLint 不会搜索配置文件,而是使用 some-other-file.js。
🌐 In this case, ESLint does not search for configuration files and instead uses some-other-file.js.
TypeScript 配置文件
🌐 TypeScript Configuration Files
对于 Deno 和 Bun,TypeScript 配置文件是原生支持的;对于 Node.js,你必须在项目中安装可选的开发依赖 jiti(版本 2.2.0 或更高)(该依赖不会被 ESLint 自动安装):
🌐 For Deno and Bun, TypeScript configuration files are natively supported; for Node.js, you must install the optional dev dependency jiti in version 2.2.0 or later in your project (this dependency is not automatically installed by ESLint):
npm
npm install --save-dev jiti
yarn
yarn add --dev jiti
pnpm
pnpm add --save-dev jiti
bun
bun add --dev jiti
然后你可以创建一个带有 .ts、.mts 或 .cts 扩展名的配置文件,并导出一个 配置对象 数组。
🌐 You can then create a configuration file with a .ts, .mts, or .cts extension, and export an array of configuration objects.
原生 TypeScript 支持
🌐 Native TypeScript Support
如果你使用的是 Node.js >= 22.13.0,你可以原生加载 TypeScript 配置文件,而不需要 jiti。这是由于 --experimental-strip-types 标志的作用。
🌐 If you’re using Node.js >= 22.13.0, you can load TypeScript configuration files natively without requiring jiti. This is possible thanks to the --experimental-strip-types flag.
由于此功能仍处于实验阶段,你还必须启用 unstable_native_nodejs_ts_config 标志。
🌐 Since this feature is still experimental, you must also enable the unstable_native_nodejs_ts_config flag.
npx --node-options='--experimental-strip-types' eslint --flag unstable_native_nodejs_ts_config
配置文件优先级
🌐 Configuration File Precedence
如果你有多个 ESLint 配置文件,ESLint 会优先考虑 JavaScript 文件而不是 TypeScript 文件。优先顺序如下:
🌐 If you have multiple ESLint configuration files, ESLint prioritizes JavaScript files over TypeScript files. The order of precedence is as follows:
eslint.config.jseslint.config.mjseslint.config.cjseslint.config.tseslint.config.mtseslint.config.cts
要覆盖此行为,请使用 --config 或 -c 命令行选项来指定不同的配置文件:
🌐 To override this behavior, use the --config or -c command line option to specify a different configuration file:
npm
npx eslint --config eslint.config.ts
yarn
yarn dlx eslint --config eslint.config.ts
pnpm
pnpm dlx eslint --config eslint.config.ts
bun
bunx eslint --config eslint.config.ts