配置文件(新)

你可以将 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.

配置文件

ESLint 配置文件名为 eslint.config.js。 它应该放在你的项目的根目录下,导出一个 配置对象 的数组。 这是一个例子:

The ESLint configuration file is named eslint.config.js. It should be placed in the root directory of your project and export an array of configuration objects. Here’s an example:

export default [
    {
        rules: {
            semi: "error",
            "prefer-const": "error"
        }
    }
];

在此示例中,配置数组仅包含一个配置对象。 配置对象启用两个规则: semiprefer-const。 这些规则适用于 ESLint 使用此配置文件处理的所有文件。

In this example, the configuration array contains 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:

module.exports = [
    {
        rules: {
            semi: "error",
            "prefer-const": "error"
        }
    }
];

配置文件还可以导出解析为配置数组的 promise。 这对于在 CommonJS 配置文件中使用 ESM 依赖非常有用,如下例所示:

The configuration file can also export a promise that resolves to the configuration array. This can be useful for using ESM dependencies in CommonJS configuration files, as in this example:

module.exports = (async () => {

    const someDependency = await import("some-esm-dependency");

    return [
        // ... use `someDependency` here
    ];

})();

配置对象

每个配置对象都包含 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:

  • files - 指示配置对象应应用于的文件的通配符模式数组。 如果未指定,则配置对象适用于与任何其他配置对象匹配的所有文件。
  • ignores - 指示配置对象不应应用于的文件的通配符模式数组。 如果未指定,则配置对象适用于 files 匹配的所有文件。
  • languageOptions - 包含与如何为 linting 配置 JavaScript 相关的设置的对象。
    • ecmaVersion - 支持的 ECMAScript 版本。 可以是任何年份(即 2022)或版本(即 5)。 对于最新支持的版本,设置为 "latest"。 (默认:"latest"
    • sourceType - JavaScript 源代码的类型。 可能的值是 "script" 用于传统脚本文件,"module" 用于 ECMAScript 模块 (ESM) 和 "commonjs" 用于 CommonJS 文件。 (默认:"module" 表示 .js.mjs 文件;"commonjs" 表示 .cjs 文件)
    • globals - 指定在 linting 期间应添加到全局作用域的其他对象的对象。
    • parser - 包含 parse() 方法或 parseForESLint() 方法的对象。 (默认:espree
    • parserOptions - 指定直接传递给解析器上的 parse()parseForESLint() 方法的其他选项的对象。 可用选项取决于解析器。
  • linterOptions - 包含与 linting 过程相关的设置的对象。
    • noInlineConfig - 一个布尔值,指示是否允许内联配置。
    • reportUnusedDisableDirectives - 一个严重性字符串,指示是否以及如何应跟踪和报告未使用的禁用和启用指令。 对于旧版兼容性,true 相当于 "warn"false 相当于 "off"。 (默认:"off"
  • processor - 包含 preprocess()postprocess() 方法的对象或指示插件内处理器名称的字符串(即 "pluginName/processorName")。
  • plugins - 包含插件名称到插件对象的名称-值映射的对象。 指定 files 时,这些插件仅对匹配的文件可用。
  • rules - 包含配置规则的对象。 当指定 filesignores 时,这些规则配置只对匹配的文件可用。
  • settings - 一个包含名称-值对信息的对象,所有规则都应使用这些信息。

指定 filesignores

你可以使用 filesignores 的组合来确定哪些文件应该应用配置对象,哪些不应该。 默认情况下,ESLint 匹配 **/*.js**/*.cjs**/*.mjs。 由于未指定 filesignores 的配置对象适用于已被任何其他配置对象匹配的所有文件,因此这些配置对象默认适用于传递给 ESLint 的任何 JavaScript 文件。 例如:

You can use a combination of files and ignores to determine which files should apply the configuration object and which should not. By default, ESLint matches **/*.js, **/*.cjs, and **/*.mjs. Because config objects that don’t specify files or ignores apply to all files that have been matched by any other configuration object, those config objects apply to any JavaScript files passed to ESLint by default. For example:

export default [
    {
        rules: {
            semi: "error"
        }
    }
];

使用此配置,semi 规则会为与 ESLint 中的默认文件匹配的所有文件启用。 因此,如果你将 example.js 传递给 ESLint,则会应用 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.)

使用 ignores 排除文件

你可以通过指定 filesignores 模式的组合来限制配置对象适用于哪些文件。 例如,你可能希望某些规则仅适用于 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:

export default [
    {
        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:

export default [
    {
        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:

export default [
    {
        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.

如果 ignores 没有使用 files,还有其他键(比如 rules),那么配置对象适用于除 ignores 中指定的文件之外的所有文件,例如:

If ignores is used without files and there are other keys (such as rules), then the configuration object applies to all files except the ones specified in ignores, for example:

export default [
    {
        ignores: ["**/*.config.js"],
        rules: {
            semi: "error"
        }
    }
];

此配置对象适用于除以 .config.js 结尾的文件之外的所有文件。 实际上,这就像将 files 设置为 **/*。 通常,如果你指定 ignores,最好始终包含 files

This configuration object applies to all 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.

使用 ignores 全局地忽略文件

如果 ignores 在配置对象中没有任何其他键的情况下使用,则模式充当全局忽略。 这是一个例子:

If ignores is used without any other keys in the configuration object, then the patterns act as global ignores. Here’s an example:

export default [
    {
        ignores: [".config/*"]
    }
];

此配置指定应忽略 .config 目录中的所有文件。 此模式添加在默认模式之后,即 ["**/node_modules/", ".git/"]

This configuration specifies that all of the files in the .config directory should be ignored. This pattern is added after the default patterns, which are ["**/node_modules/", ".git/"].

你还可以取消忽略默认模式忽略的文件和目录。 例如,此配置忽略 node_modules/mylibrary

You can also unignore files and directories that are ignored by the default patterns. For example, this config unignores node_modules/mylibrary:

export default [
    {
        ignores: [
            "!node_modules/",           // unignore `node_modules/` directory
            "node_modules/*",           // ignore its content
            "!node_modules/mylibrary/"  // unignore `node_modules/mylibrary` directory
        ]
    }
];

请注意,只有全局 ignores 模式可以匹配目录。 特定于配置的 ignores 模式将仅匹配文件名。

Note that only global ignores patterns can match directories. ignores patterns that are specific to a configuration will only match file names.

级联配置对象

当多个配置对象与给定文件名匹配时,配置对象将与在发生冲突时覆盖先前对象的后续对象合并。 例如:

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:

export default [
    {
        files: ["**/*.js"],
        languageOptions: {
            globals: {
                MY_CUSTOM_GLOBAL: "readonly"
            }
        }
    },
    {
        files: ["tests/**/*.js"],
        languageOptions: {
            globals: {
                it: "readonly",
                describe: "readonly"
            }
        }
    }
];

使用此配置,所有 JavaScript 文件都定义了一个名为 MY_CUSTOM_GLOBAL 的自定义全局对象,而 tests 目录中的那些 JavaScript 文件将 itdescribe 定义为除 MY_CUSTOM_GLOBAL 之外的全局对象。 对于测试目录中的任何 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.

配置检查器选项

可以使用 linterOptions 对象配置特定于 linting 过程的选项。 这些影响 linting 如何进行,而不影响文件源代码的解释方式。

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.

禁用内联配置

内联配置是使用 /*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:

export default [
    {
        files: ["**/*.js"],
        linterOptions: {
            noInlineConfig: true
        }
    }
];

报告未使用的禁用指令

禁用和启用指令(例如 /*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:

export default [
    {
        files: ["**/*.js"],
        linterOptions: {
            reportUnusedDisableDirectives: "error"
        }
    }
];

您可以使用 --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".

配置语言选项

可以使用 languageOptions 对象配置特定于 ESLint 如何评估 JavaScript 代码的选项。

Options specific to how ESLint evaluates your JavaScript code can be configured using the languageOptions object.

配置 JavaScript 版本

要配置 ESLint 用于评估 JavaScript 的 JavaScript (ECMAScript) 版本,请使用 ecmaVersion 属性。 该属性确定哪些全局变量和语法在你的代码中有效,可以设置为版本号(例如 6)、年份号(例如 2022)或 "latest"(对于 ESLint 支持的最新版本)。 默认情况下,ecmaVersion 设置为 "latest",建议保留此默认值,除非你需要确保将 JavaScript 代码评估为旧版本。 例如,一些较旧的运行时可能只允许 ECMAScript 5,在这种情况下,你可以像这样配置 ESLint:

To configure the version of JavaScript (ECMAScript) that ESLint uses to evaluate your JavaScript, use the ecmaVersion property. This property determines which global variables and syntax are valid in your code and can be set to the version number (such as 6), the year number (such as 2022), or "latest" (for the most recent version that ESLint supports). By default, ecmaVersion is set to "latest" and it’s recommended to keep this default unless you need to ensure that your JavaScript code is evaluated as an older version. For example, some older runtimes might only allow ECMAScript 5, in which case you can configure ESLint like this:

export default [
    {
        files: ["**/*.js"],
        languageOptions: {
            ecmaVersion: 5
        }
    }
];

配置 JavaScript 源代码类型

ESLint 可以通过以下三种方式之一评估你的代码:

ESLint can evaluate your code in one of three ways:

  1. ECMAScript 模块 (ESM) - 你的代码具有模块作用域,并且在严格模式下运行。
  2. CommonJS - 你的代码具有顶层函数作用域并以非严格模式运行。
  3. 脚本 - 你的代码具有共享的全局作用域并以非严格模式运行。

你可以通过指定 sourceType 属性来指定你的代码打算在哪些模式下运行。 此属性可以设置为 "module""commonjs""script"。 默认情况下,对于 .js.mjs 文件,sourceType 设置为 "module",对于 .cjs 文件,设置为 "commonjs"。 这是一个例子:

You can specify which of these modes your code is intended to run in by specifying the sourceType property. This property can be set to "module", "commonjs", or "script". By default, sourceType is set to "module" for .js and .mjs files and is set to "commonjs" for .cjs files. Here’s an example:

export default [
    {
        files: ["**/*.js"],
        languageOptions: {
            sourceType: "script"
        }
    }
];

配置自定义解析器及其选项

在许多情况下,你可以使用 ESLint 附带的默认解析器来解析你的 JavaScript 代码。 你可以选择使用 parser 属性覆盖默认解析器。 parser 属性必须是包含 parse() 方法或 parseForESLint() 方法的对象。 例如,你可以使用 @babel/eslint-parser 包来允许 ESLint 解析实验性语法:

In many cases, you can use the default parser that ESLint ships with for parsing your JavaScript code. You can optionally override the default parser by using the parser property. The parser property must be an object containing either a parse() method or a parseForESLint() method. For example, you can use the @babel/eslint-parser package to allow ESLint to parse experimental syntax:

import babelParser from "@babel/eslint-parser";

export default [
    {
        files: ["**/*.js", "**/*.mjs"],
        languageOptions: {
            parser: babelParser
        }
    }
];

此配置确保使用 Babel 解析器而不是默认的 Espree 解析器来解析所有以 .js.mjs 结尾的文件。

This configuration ensures that the Babel parser, rather than the default Espree parser, is used to parse all files ending with .js and .mjs.

你还可以使用 parserOptions 属性将选项直接传递给自定义解析器。 此属性是一个对象,其名称-值对特定于你正在使用的解析器。 对于 Babel 解析器,你可以传入如下选项:

You can also pass options directly to the custom parser by using the parserOptions property. This property is an object whose name-value pairs are specific to the parser that you are using. For the Babel parser, you might pass in options like this:

import babelParser from "@babel/eslint-parser";

export default [
    {
        files: ["**/*.js", "**/*.mjs"],
        languageOptions: {
            parser: babelParser,
            parserOptions: {
                requireConfigFile: false,
                babelOptions: {
                    babelrc: false,
                    configFile: false,
                    // your babel options
                    presets: ["@babel/preset-env"],
                }
            }
        }
    }
];

配置全局变量

要在配置对象中配置全局变量,请将 globals 配置属性设置为一个对象,该对象包含为你要使用的每个全局变量命名的键。 对于每个全局变量键,设置相应的值等于 "writable" 以允许变量被覆盖或 "readonly" 不允许覆盖。 例如:

To configure global variables inside of a configuration object, set the globals configuration property to an object containing keys named for each of the global variables you want to use. For each global variable key, set the corresponding value equal to "writable" to allow the variable to be overwritten or "readonly" to disallow overwriting. For example:

export default [
    {
        files: ["**/*.js"],
        languageOptions: {
            globals: {
                var1: "writable",
                var2: "readonly"
            }
        }
    }
];

这些示例允许在你的代码中覆盖 var1,但不允许对 var2 进行覆盖。

These examples allow var1 to be overwritten in your code, but disallow it for var2.

可以使用字符串 "off" 禁用全局变量。 例如,在大多数 ES2015 全局变量可用但 Promise 不可用的环境中,你可以使用以下配置:

Globals can be disabled with the string "off". For example, in an environment where most ES2015 globals are available but Promise is unavailable, you might use this config:

export default [
    {
        languageOptions: {
            globals: {
                Promise: "off"
            }
        }
    }
];

由于历史原因,布尔值 false 和字符串值 "readable" 等价于 "readonly"。 类似地,布尔值 true 和字符串值 "writeable" 等价于 "writable"。 但是,不推荐使用旧值。

For historical reasons, the boolean value false and the string value "readable" are equivalent to "readonly". Similarly, the boolean value true and the string value "writeable" are equivalent to "writable". However, the use of older values is deprecated.

预定义的全局变量

除了基于配置的 languageOptions.ecmaVersion 自动启用的 ECMAScript 标准内置全局变量外,ESLint 不提供预定义的全局变量集。 你可以使用 globals 包为特定环境额外启用所有全局变量。 例如,这里是如何将 console 以及其他浏览器全局变量添加到你的配置中。

Apart from the ECMAScript standard built-in globals, which are automatically enabled based on the configured languageOptions.ecmaVersion, ESLint doesn’t provide predefined sets of global variables. You can use the globals package to additionally enable all globals for a specific environment. For example, here is how you can add console, amongst other browser globals, into your configuration.

import globals from "globals";
export default [
    {
        languageOptions: {
            globals: {
                ...globals.browser
            }
        }
    }
];

在配置中使用插件

插件用于跨 ESLint 项目共享规则、处理器、配置、解析器等。

Plugins are used to share rules, processors, configurations, parsers, and more across ESLint projects.

使用插件规则

你可以使用插件中包含的特定规则。 为此,请使用 plugins 键在配置对象中指定插件。 plugin 键的值是一个对象,其中插件的名称是属性名称,值是插件对象本身。 这是一个例子:

You can use specific rules included in a plugin. To do this, specify the plugin in a configuration object using the plugins key. The value for the plugin key is an object where the name of the plugin is the property name and the value is the plugin object itself. Here’s an example:

import jsdoc from "eslint-plugin-jsdoc";

export default [
    {
        files: ["**/*.js"],
        plugins: {
            jsdoc: jsdoc
        },
        rules: {
            "jsdoc/require-description": "error",
            "jsdoc/check-values": "error"
        }
    }
];

在此配置中,JSDoc 插件被定义为名称 jsdoc。 每个规则名称中的前缀 jsdoc/ 表示该规则来自具有该名称的插件,而不是来自 ESLint 本身。

In this configuration, the JSDoc plugin is defined to have the name jsdoc. The prefix jsdoc/ in each rule name indicates that the rule is coming from the plugin with that name rather than from ESLint itself.

因为插件的名字和插件对象都是 jsdoc,你也可以把配置简写成这样:

Because the name of the plugin and the plugin object are both jsdoc, you can also shorten the configuration to this:

import jsdoc from "eslint-plugin-jsdoc";

export default [
    {
        files: ["**/*.js"],
        plugins: {
            jsdoc
        },
        rules: {
            "jsdoc/require-description": "error",
            "jsdoc/check-values": "error"
        }
    }
];

虽然这是最常见的约定,但你不需要使用插件规定的相同名称。 你可以指定任何你喜欢的前缀,例如:

While this is the most common convention, you don’t need to use the same name that the plugin prescribes. You can specify any prefix that you’d like, such as:

import jsdoc from "eslint-plugin-jsdoc";

export default [
    {
        files: ["**/*.js"],
        plugins: {
            jsd: jsdoc
        },
        rules: {
            "jsd/require-description": "error",
            "jsd/check-values": "error"
        }
    }
];

此配置对象使用 jsd 作为前缀插件,而不是 jsdoc

This configuration object uses jsd as the prefix plugin instead of jsdoc.

使用插件中包含的配置

你可以通过将配置直接添加到 eslint.config.js 配置数组来使用插件中包含的配置。 通常,你这样做是为了插件的推荐配置。 这是一个例子:

You can use a configuration included in a plugin by adding that configuration directly to the eslint.config.js configurations array. Often, you do this for a plugin’s recommended configuration. Here’s an example:

import jsdoc from "eslint-plugin-jsdoc";

export default [
    // configuration included in plugin
    jsdoc.configs["flat/recommended"],
    // other configuration objects...
    {
        files: ["**/*.js"],
        plugins: {
            jsdoc: jsdoc
        },
        rules: {
            "jsdoc/require-description": "warn",
        }
    }
];

使用处理器

处理器允许 ESLint 将文本转换为 ESLint 可以 lint 的代码片段。 你可以通过定义一个 processor 属性来指定用于给定文件类型的处理器,该属性包含格式为 "pluginName/processorName" 的处理器名称以引用插件中的处理器或包含 preprocess()postprocess() 方法的对象。 例如,要从 Markdown 文件中提取 JavaScript 代码块,你可以将其添加到你的配置中:

Processors allow ESLint to transform text into pieces of code that ESLint can lint. You can specify the processor to use for a given file type by defining a processor property that contains either the processor name in the format "pluginName/processorName" to reference a processor in a plugin or an object containing both a preprocess() and a postprocess() method. For example, to extract JavaScript code blocks from a Markdown file, you might add this to your configuration:

import markdown from "eslint-plugin-markdown";

export default [
    {
        files: ["**/*.md"],
        plugins: {
            markdown
        },
        processor: "markdown/markdown",
        settings: {
            sharedData: "Hello"
        }
    }
];

该配置对象指定名为 "markdown" 的插件中包含一个名为 "markdown" 的处理器。 该配置将处理器应用于所有以 .md 结尾的文件。

This configuration object specifies that there is a processor called "markdown" contained in the plugin named "markdown". The configuration applies the processor to all files ending with .md.

处理器可以生成命名代码块,作为配置对象中的文件名,例如 0.js1.js。 ESLint 将这样的命名代码块作为原始文件的子文件处理。 你可以为命名代码块指定其他配置对象。 例如,以下对 markdown 文件中以 .js 结尾的命名代码块禁用 strict 规则。

Processors may make named code blocks that function as filenames in configuration objects, such as 0.js and 1.js. ESLint handles such a named code block as a child of the original file. You can specify additional configuration objects for named code blocks. For example, the following disables the strict rule for the named code blocks which end with .js in markdown files.

import markdown from "eslint-plugin-markdown";

export default [
    {
        files: ["**/*.md"],
        plugins: {
            markdown
        },
        processor: "markdown/markdown",
        settings: {
            sharedData: "Hello"
        }
    },

    // applies only to code blocks
    {
        files: ["**/*.md/*.js"],
        rules: {
            strict: "off"
        }
    }
];

配置规则

你可以通过添加一个 rules 属性来在配置对象中配置任意数量的规则,该属性包含一个带有你的规则配置的对象。 此对象中的名称是规则的名称,值是每个规则的配置。 这是一个例子:

You can configure any number of rules in a configuration object by add 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:

export default [
    {
        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:

export default [
    {
        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.

规则严重性

你可以为规则指定三种可能的严重性

There are three possible severities you can specify for a rule

  • "error" (或 2)- 报告的问题应被视为错误。 使用 ESLint CLI 时,错误会导致 CLI 以非零代码退出。
  • "warn" (或 1)- 报告的问题应被视为警告。 使用 ESLint CLI 时,会报告警告,但不会更改退出代码。 如果仅报告警告,则退出代码为 0。
  • "off" (或 0)- 应完全关闭该规则。

规则配置级联

当多个配置对象指定相同的规则时,规则配置将与后面的对象合并,优先于任何先前的对象。 例如:

When more than one configuration object specifies the same rule, the rule configuration is merged with the later object taking precedence over any previous objects. For example:

export default [
    {
        rules: {
            semi: ["error", "never"]
        }
    },
    {
        rules: {
            semi: ["warn", "always"]
        }
    }
];

使用此配置,semi 的最终规则配置是 ["warn", "always"],因为它出现在数组的最后。 该数组指示配置用于严重性和任何选项。 你可以通过仅定义字符串或数字来仅更改严重性,如下例所示:

Using this configuration, the final rule configuration for semi is ["warn", "always"] because it appears last in the array. The array indicates that the configuration is for the severity and any options. You can change just the severity by defining only a string or number, as in this example:

export default [
    {
        rules: {
            semi: ["error", "never"]
        }
    },
    {
        rules: {
            semi: "warn"
        }
    }
];

这里,第二个配置对象只覆盖了严重性,所以 semi 的最终配置是 ["warn", "never"]

Here, the second configuration object only overrides the severity, so the final configuration for semi is ["warn", "never"].

配置共享设置

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:

export default [
    {
        settings: {
            sharedData: "Hello"
        }
    }
];

使用预定义的配置

ESLint 有两个预定义的 JavaScript 配置:

ESLint has two predefined configurations for JavaScript:

  • js.configs.recommended - 启用 ESLint 建议每个人使用的规则,以避免潜在的错误
  • js.configs.all - 启用 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:

import js from "@eslint/js";

export default [
    js.configs.recommended,
    {
        rules: {
            semi: ["warn", "always"]
        }
    }
];

在这里,首先应用 js.configs.recommended 预定义的配置,然后另一个配置对象为 semi 添加所需的配置。

Here, the js.configs.recommended predefined configuration is applied first and then another configuration object adds the desired configuration for semi.

你可以通过使用 files 键指定配置对象,将这些预定义配置仅应用于文件子集,如下所示:

You can apply these predefined configs to just a subset of files by specifying a config object with a files key, like this:

import js from "@eslint/js";

export default [
    {
        files: ["**/src/safe/*.js"],
        ...js.configs.recommended
    }
];

配置文件解析

当 ESLint 在命令行上运行时,它首先检查 eslint.config.js 的当前工作目录。 如果找不到该文件,它会查找该文件的下一个父目录。 此搜索将继续,直到找到文件或到达根目录。

When ESLint is run on the command line, it first checks the current working directory for eslint.config.js. If the file is not found, it looks to the next parent directory for the file. This search continues until either the file is found or the root directory is reached.

你可以通过将 ESLINT_USE_FLAT_CONFIG 环境变量设置为 true 并在命令行上使用 -c--config 选项指定备用配置文件来阻止对 eslint.config.js 的搜索,例如:

You can prevent this search for eslint.config.js by setting the ESLINT_USE_FLAT_CONFIG environment variable to true and using the -c or --config option on the command line to specify an alternate configuration file, such as:

ESLINT_USE_FLAT_CONFIG=true npx eslint --config some-other-file.js **/*.js

在这种情况下,ESLint 不会搜索 eslint.config.js,而是使用 some-other-file.js

In this case, ESLint does not search for eslint.config.js and instead uses some-other-file.js.