source: imaps-frontend/node_modules/@humanwhocodes/config-array/README.md@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 14.0 KB
Line 
1# Config Array
2
3by [Nicholas C. Zakas](https://humanwhocodes.com)
4
5If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
6
7## Description
8
9A 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.
10
11## Background
12
13In 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.
14
15The 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:
16
17```js
18export default [
19
20 // match all JSON files
21 {
22 name: "JSON Handler",
23 files: ["**/*.json"],
24 handler: jsonHandler
25 },
26
27 // match only package.json
28 {
29 name: "package.json Handler",
30 files: ["package.json"],
31 handler: packageJsonHandler
32 }
33];
34```
35
36In 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).
37
38## Installation
39
40You can install the package using npm or Yarn:
41
42```bash
43npm install @humanwhocodes/config-array --save
44
45# or
46
47yarn add @humanwhocodes/config-array
48```
49
50## Usage
51
52First, import the `ConfigArray` constructor:
53
54```js
55import { ConfigArray } from "@humanwhocodes/config-array";
56
57// or using CommonJS
58
59const { ConfigArray } = require("@humanwhocodes/config-array");
60```
61
62When 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:
63
64```js
65const configFilename = path.resolve(process.cwd(), "my.config.js");
66const { default: rawConfigs } = await import(configFilename);
67const configs = new ConfigArray(rawConfigs, {
68
69 // the path to match filenames from
70 basePath: process.cwd(),
71
72 // additional items in each config
73 schema: mySchema
74});
75```
76
77This 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 directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`.
78
79### Specifying a Schema
80
81The `schema` option is required for you to use additional properties in config objects. The schema is an 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:
82
83```js
84const configFilename = path.resolve(process.cwd(), "my.config.js");
85const { default: rawConfigs } = await import(configFilename);
86
87const mySchema = {
88
89 // define the handler key in configs
90 handler: {
91 required: true,
92 merge(a, b) {
93 if (!b) return a;
94 if (!a) return b;
95 },
96 validate(value) {
97 if (typeof value !== "function") {
98 throw new TypeError("Function expected.");
99 }
100 }
101 }
102};
103
104const configs = new ConfigArray(rawConfigs, {
105
106 // the path to match filenames from
107 basePath: process.cwd(),
108
109 // additional item schemas in each config
110 schema: mySchema,
111
112 // additional config types supported (default: [])
113 extraConfigTypes: ["array", "function"];
114});
115```
116
117### Config Arrays
118
119Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as:
120
121```js
122export default [
123
124 // JS config
125 {
126 files: ["**/*.js"],
127 handler: jsHandler
128 },
129
130 // JSON configs
131 [
132
133 // match all JSON files
134 {
135 name: "JSON Handler",
136 files: ["**/*.json"],
137 handler: jsonHandler
138 },
139
140 // match only package.json
141 {
142 name: "package.json Handler",
143 files: ["package.json"],
144 handler: packageJsonHandler
145 }
146 ],
147
148 // filename must match function
149 {
150 files: [ filePath => filePath.endsWith(".md") ],
151 handler: markdownHandler
152 },
153
154 // filename must match all patterns in subarray
155 {
156 files: [ ["*.test.*", "*.js"] ],
157 handler: jsTestHandler
158 },
159
160 // filename must not match patterns beginning with !
161 {
162 name: "Non-JS files",
163 files: ["!*.js"],
164 settings: {
165 js: false
166 }
167 }
168];
169```
170
171In 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.
172
173If 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.)
174
175If 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.
176
177If 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 get a `settings.js` property set to `false`.
178
179You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example:
180
181```js
182export default [
183
184 // Always ignored
185 {
186 ignores: ["**/.git/**", "**/node_modules/**"]
187 },
188
189 // .eslintrc.js file is ignored only when .js file matches
190 {
191 files: ["**/*.js"],
192 ignores: [".eslintrc.js"]
193 handler: jsHandler
194 }
195];
196```
197
198You can use negated patterns in `ignores` to exclude a file that was already ignored, such as:
199
200```js
201export default [
202
203 // Ignore all JSON files except tsconfig.json
204 {
205 files: ["**/*"],
206 ignores: ["**/*.json", "!tsconfig.json"]
207 },
208
209];
210```
211
212### Config Functions
213
214Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. 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:
215
216```js
217export default [
218
219 // JS config
220 {
221 files: ["**/*.js"],
222 handler: jsHandler
223 },
224
225 // JSON configs
226 function (context) {
227 return [
228
229 // match all JSON files
230 {
231 name: context.name + " JSON Handler",
232 files: ["**/*.json"],
233 handler: jsonHandler
234 },
235
236 // match only package.json
237 {
238 name: context.name + " package.json Handler",
239 files: ["package.json"],
240 handler: packageJsonHandler
241 }
242 ];
243 }
244];
245```
246
247When a config array is normalized, each function is executed and replaced in the config array with the return value.
248
249**Note:** Config functions can also be async.
250
251### Normalizing Config Arrays
252
253Once 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.
254
255To normalize a config array, call the `normalize()` method and pass in a context object:
256
257```js
258await configs.normalize({
259 name: "MyApp"
260});
261```
262
263The `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.
264
265If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise:
266
267```js
268await configs.normalizeSync({
269 name: "MyApp"
270});
271```
272
273**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.
274
275### Getting Config for a File
276
277To 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:
278
279```js
280// pass in absolute filename
281const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json"));
282```
283
284The 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.
285
286A few things to keep in mind:
287
288* You must pass in the absolute filename to get a config for.
289* The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified.
290* The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
291* A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry ending with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches.
292
293## Determining Ignored Paths
294
295You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the absolute path of any file, as in this example:
296
297```js
298const ignored = configs.isFileIgnored('/foo/bar/baz.txt');
299```
300
301A file is considered ignored if any of the following is true:
302
303* **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored.
304* **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored.
305* **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
306* **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
307* **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
308
309For directories, use the `isDirectoryIgnored()` method and pass in the absolute path of any directory, as in this example:
310
311```js
312const ignored = configs.isDirectoryIgnored('/foo/bar/');
313```
314
315A directory is considered ignored if any of the following is true:
316
317* **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored.
318* **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored.
319* **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
320* **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
321* **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
322
323**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are *not* ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`.
324
325## Caching Mechanisms
326
327Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways:
328
3291. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in.
3302. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`.
331
332## Acknowledgements
333
334The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
335
336* Teddy Katz (@not-an-aardvark)
337* Toru Nagashima (@mysticatea)
338* Kai Cataldo (@kaicataldo)
339
340## License
341
342Apache 2.0
Note: See TracBrowser for help on using the repository browser.