组合配置

在许多情况下,你不会从头开始编写 ESLint 配置文件,而是将使用预定义和可共享配置的组合以及你自己的覆盖来为项目创建配置。本页介绍了一些可用于在配置文件中组合配置的模式。

¥In many cases, you won’t write an ESLint config file from scratch, but rather, you’ll use a combination of predefined and shareable configs along with your own overrides to create the config for your project. This page explains some of the patterns you can use to combine configs in your configuration file.

应用配置对象

¥Apply a Config Object

如果你从另一个模块导入 配置对象,则可以通过创建一个带有 files 键的新对象,并使用 extends 键合并导入对象的其余属性,从而将其仅应用于部分文件。例如:

¥If you are importing a config object from another module, you can apply it to just a subset of files by creating a new object with a files key and using the extends key to merge in the rest of the properties from the imported object. For example:

// 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" 应用于符合模式 "**/*.js" 的文件,然后再为 no-unused-vars 添加所需的配置。

¥Here, the "js/recommended" predefined configuration is applied to files that match the pattern "**/*.js" first and then adds the desired configuration for no-unused-vars.

应用配置数组

¥Apply a Config Array

如果你从另一个模块导入 配置数组,则可以使用 extends 键将配置数组(配置对象数组)仅应用于部分文件。例如:

¥If you are importing a config array from another module, you can apply a config array (an array of configuration objects) to just a subset of files by using the extends key. For example:

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

export default defineConfig([
	{
		files: ["**/*.js"],
		extends: [exampleConfigs],
		rules: {
			"no-unused-vars": "warn",
		},
	},
]);

这里,exampleConfigs 共享配置首先应用于匹配“**/*.js"”模式的文件,然后另一个配置对象会添加 no-unused-vars 所需的配置。

¥Here, the exampleConfigs shareable configuration is applied to files that match the pattern "**/*.js" first and then another configuration object adds the desired configuration for no-unused-vars.