配置文件

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

  • eslint.config.mjs

  • eslint.config.cjs

它应该放在你的项目的根目录下,导出一个 配置对象 的数组。这是一个例子:

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

// eslint.config.js
module.exports = [
    {
        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 - 配置对象的名称。这在错误消息和配置检查器中使用,以帮助识别正在使用哪个配置对象。(命名约定)

    ¥name - A name for the configuration object. This is used in error messages and config inspector to help identify which configuration object is being used. (Naming Convention)

  • files - 指示配置对象应应用于的文件的通配符模式数组。如果未指定,则配置对象适用于与任何其他配置对象匹配的所有文件。

    ¥files - An array of glob patterns indicating the files that the configuration object should apply to. If not specified, the configuration object applies to all files matched by any other configuration object.

  • ignores - 指示配置对象不应应用于的文件的通配符模式数组。如果未指定,则配置对象适用于 files 匹配的所有文件。

    ¥ignores - An array of glob patterns indicating the files that the configuration object should not apply to. If not specified, the configuration object applies to all files matched by files.

  • languageOptions - 包含与如何为代码检查配置 JavaScript 相关的设置的对象。

    ¥languageOptions - An object containing settings related to how JavaScript is configured for linting.

    • ecmaVersion - 支持的 ECMAScript 版本。可以是任何年份(即 2022)或版本(即 5)。对于最新支持的版本,设置为 "latest"。(默认:"latest"

      ¥ecmaVersion - The version of ECMAScript to support. May be any year (i.e., 2022) or version (i.e., 5). Set to "latest" for the most recent supported version. (default: "latest")

    • sourceType - JavaScript 源代码的类型。可能的值是 "script" 用于传统脚本文件,"module" 用于 ECMAScript 模块 (ESM) 和 "commonjs" 用于 CommonJS 文件。(默认:"module" 用于 .js.mjs 文件;"commonjs" 用于 .cjs 文件)

      ¥sourceType - The type of JavaScript source code. Possible values are "script" for traditional script files, "module" for ECMAScript modules (ESM), and "commonjs" for CommonJS files. (default: "module" for .js and .mjs files; "commonjs" for .cjs files)

    • globals - 指定在代码检查期间应添加到全局作用域的其他对象的对象。

      ¥globals - An object specifying additional objects that should be added to the global scope during linting.

    • parser - 包含 parse() 方法或 parseForESLint() 方法的对象。(默认:espree

      ¥parser - An object containing a parse() method or a parseForESLint() method. (default: espree)

    • parserOptions - 指定直接传递给解析器上的 parse()parseForESLint() 方法的其他选项的对象。可用选项取决于解析器。

      ¥parserOptions - An object specifying additional options that are passed directly to the parse() or parseForESLint() method on the parser. The available options are parser-dependent.

  • linterOptions - 包含与代码检查过程相关的设置的对象。

    ¥linterOptions - An object containing settings related to the linting process.

    • noInlineConfig - 一个布尔值,指示是否允许内联配置。

      ¥noInlineConfig - A Boolean value indicating if inline configuration is allowed.

    • reportUnusedDisableDirectives - 一个严重性字符串,指示是否以及如何应跟踪和报告未使用的禁用和启用指令。对于旧版兼容性,true 相当于 "warn"false 相当于 "off"。(默认值:"warn")。

      ¥reportUnusedDisableDirectives - A severity string indicating if and how unused disable and enable directives should be tracked and reported. For legacy compatibility, true is equivalent to "warn" and false is equivalent to "off". (default: "warn").

  • processor - 包含 preprocess()postprocess() 方法的对象或指示插件内处理器名称的字符串(即 "pluginName/processorName")。

    ¥processor - Either an object containing preprocess() and postprocess() methods or a string indicating the name of a processor inside of a plugin (i.e., "pluginName/processorName").

  • plugins - 包含插件名称到插件对象的名称-值映射的对象。指定 files 时,这些插件仅对匹配的文件可用。

    ¥plugins - An object containing a name-value mapping of plugin names to plugin objects. When files is specified, these plugins are only available to the matching files.

  • rules - 包含配置规则的对象。当指定 filesignores 时,这些规则配置只对匹配的文件可用。

    ¥rules - An object containing the configured rules. When files or ignores are specified, these rule configurations are only available to the matching files.

  • settings - 一个包含名称-值对信息的对象,所有规则都应使用这些信息。

    ¥settings - An object containing name-value pairs of information that should be available to all rules.

指定 filesignores

¥Specifying files and ignores

你可以使用 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:

// eslint.config.js
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 排除文件

¥Excluding files with 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:

// eslint.config.js
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 全局地忽略文件

¥Globally ignoring files with 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:

// eslint.config.js
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/"].

有关配置规则的更多信息,请参阅 忽略文件

¥For more information on configuring rules, see Ignore Files.

级联配置对象

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

配置代码检查器选项

¥Configuring Linter Options

可以使用 linterOptions 对象配置特定于代码检查过程的选项。这些影响 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.

禁用内联配置

¥Disabling 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
export default [
    {
        files: ["**/*.js"],
        linterOptions: {
            noInlineConfig: true
        }
    }
];

报告未使用的禁用指令

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

配置规则

¥Configuring Rules

你可以通过添加一个 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:

// eslint.config.js
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:

// eslint.config.js
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.

有关配置规则的更多信息,请参阅 配置规则

¥For more information on configuring rules, see Configure Rules.

配置共享设置

¥Configuring 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
export default [
    {
        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"
        }
    }
];

使用预定义配置

¥Using Predefined Configurations

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

¥ESLint has two predefined configurations for JavaScript:

  • js.configs.recommended - 启用 ESLint 建议每个人使用的规则,以避免潜在的错误

    ¥js.configs.recommended - enables the rules that ESLint recommends everyone use to avoid potential errors

  • js.configs.all - 启用 ESLint 附带的所有规则

    ¥js.configs.all - enables all of the rules shipped with 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";

export default [
    js.configs.recommended,
    {
        rules: {
            "no-unused-vars": "warn"
        }
    }
];

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

¥Here, the js.configs.recommended predefined configuration is applied first and then another configuration object adds the desired configuration for no-unused-vars.

有关如何将预定义配置与你的偏好相结合的更多信息,请参阅 组合配置

¥For more information on how to combine predefined configs with your preferences, please see Combine Configs.

配置命名约定

¥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",
                file: ["src/**/*.js"],
                rules: {
                    "no-unused-vars": "error"
                }
            }
        ]
    }
}

使用可共享的配置包

¥Using 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";

export default [
    exampleConfig,

    // your modifications
    {
        rules: {
            "no-unused-vars": "warn"
        }
    }
];

在此示例中,exampleConfig 是一个对象,因此你将其直接插入到配置数组中。

¥In this example, exampleConfig is an object, so you insert it directly into the configuration array.

某些可共享配置将导出一个数组,在这种情况下,你需要使用扩展运算符将这些项目插入到配置数组中。例如:

¥Some shareable configurations will export an array instead, in which case you’ll need to use the spread operator to insert those items into the configuration array. For example:

// eslint.config.js
import exampleConfigs from "eslint-config-example";

export default [
    ...exampleConfigs,

    // your modifications
    {
        rules: {
            "no-unused-vars": "warn"
        }
    }
];

请参阅你正在使用的可共享配置包的文档,以确定它是导出对象还是数组。

¥Please refer to the documentation for the shareable configuration package you’re using to determine whether it is exporting an object or an array.

有关如何将可共享配置与你的偏好相结合的更多信息,请参阅 组合配置

¥For more information on how to combine shareable configs with your preferences, please see Combine Configs.

配置文件解析

¥Configuration File Resolution

当 ESLint 在命令行上运行时,它首先检查 eslint.config.js 的当前工作目录。如果找到该文件,则搜索停止,否则检查 eslint.config.mjs。如果找到该文件,则搜索停止,否则检查 eslint.config.cjs。如果没有找到任何文件,它将检查每个文件的父目录。此搜索将继续,直到找到配置文件或到达根目录。

¥When ESLint is run on the command line, it first checks the current working directory for eslint.config.js. If that file is found, then the search stops, otherwise it checks for eslint.config.mjs. If that file is found, then the search stops, otherwise it checks for eslint.config.cjs. If none of the files are not found, it checks the parent directory for each file. This search continues until either a config file is found or the root directory is reached.

你可以通过在命令行上使用 -c--config 选项指定备用配置文件来阻止搜索 eslint.config.js,例如:

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

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.