3 by [Nicholas C. Zakas](https://humanwhocodes.com)
5 If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
9 A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
13 In 2019, I submitted an [ESLint RFC](https://github.com/eslint/rfcs/pull/9) proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born.
15 The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
20 // match all JSON files
27 // match only package.json
29 name: "package.json Handler",
30 files: ["package.json"],
31 handler: packageJsonHandler
36 In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
40 You can install the package using npm or Yarn:
43 npm install @humanwhocodes/config-array --save
47 yarn add @humanwhocodes/config-array
52 First, import the `ConfigArray` constructor:
55 import { ConfigArray } from "@humanwhocodes/config-array";
59 const { ConfigArray } = require("@humanwhocodes/config-array");
62 When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
65 const configFilename = path.resolve(process.cwd(), "my.config.js");
66 const { default: rawConfigs } = await import(configFilename);
67 const configs = new ConfigArray(rawConfigs, {
69 // the path to match filenames from
70 basePath: process.cwd(),
72 // additional items in each config
77 This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directoy in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`.
79 ### Specifying a Schema
81 The `schema` option is required for you to use additional properties in config objects. The schema is object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@humanwhocodes/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
84 const configFilename = path.resolve(process.cwd(), "my.config.js");
85 const { default: rawConfigs } = await import(configFilename);
89 // define the handler key in configs
97 if (typeof value !== "function") {
98 throw new TypeError("Function expected.");
104 const configs = new ConfigArray(rawConfigs, {
106 // the path to match filenames from
107 basePath: process.cwd(),
109 // additional items in each config
116 Config arrays can be multidimensional, so it's possible for a config array to contain another config array, such as:
130 // match all JSON files
132 name: "JSON Handler",
133 files: ["**/*.json"],
137 // match only package.json
139 name: "package.json Handler",
140 files: ["package.json"],
141 handler: packageJsonHandler
145 // filename must match function
147 files: [ filePath => filePath.endsWith(".md") ],
148 handler: markdownHandler
151 // filename must match all patterns in subarray
153 files: [ ["*.test.*", "*.js"] ],
154 handler: jsTestHandler
157 // filename must not match patterns beginning with !
159 name: "Non-JS files",
168 In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
170 If the `files` array contains a function, then that function is called with the absolute path of the file and is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
172 If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
174 If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically getting a `settings.js` property set to `false`.
178 Config arrays can also include config functions. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
193 // match all JSON files
195 name: context.name + " JSON Handler",
196 files: ["**/*.json"],
200 // match only package.json
202 name: context.name + " package.json Handler",
203 files: ["package.json"],
204 handler: packageJsonHandler
211 When a config array is normalized, each function is executed and replaced in the config array with the return value.
213 **Note:** Config functions cannot be async. This will be added in a future version.
215 ### Normalizing Config Arrays
217 Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
219 To normalize a config array, call the `normalize()` method and pass in a context object:
222 await configs.normalize({
227 The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
229 **Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
231 ### Getting Config for a File
233 To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
236 // pass in absolute filename
237 const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json"));
240 The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
242 A few things to keep in mind:
244 * You must pass in the absolute filename to get a config for.
245 * The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified.
246 * The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
250 The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
252 * Teddy Katz (@not-an-aardvark)
253 * Toru Nagashima (@mysticatea)
254 * Kai Cataldo (@kaicataldo)