source: frontend/node_modules/cosmiconfig/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 19.3 KB
Line 
1# cosmiconfig
2
3[![Build Status](https://img.shields.io/travis/davidtheclark/cosmiconfig/main.svg?label=unix%20build)](https://travis-ci.org/davidtheclark/cosmiconfig) [![Build status](https://img.shields.io/appveyor/ci/davidtheclark/cosmiconfig/main.svg?label=windows%20build)](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/main)
4[![codecov](https://codecov.io/gh/davidtheclark/cosmiconfig/branch/main/graph/badge.svg)](https://codecov.io/gh/davidtheclark/cosmiconfig)
5
6Cosmiconfig searches for and loads configuration for your program.
7
8It features smart defaults based on conventional expectations in the JavaScript ecosystem.
9But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
10
11By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following:
12
13- a `package.json` property
14- a JSON or YAML, extensionless "rc file"
15- an "rc file" with the extensions `.json`, `.yaml`, `.yml`, `.js`, or `.cjs`
16- any of the above two inside a `.config` subdirectory
17- a `.config.js` or `.config.cjs` CommonJS module
18
19For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
20
21- a `myapp` property in `package.json`
22- a `.myapprc` file in JSON or YAML format
23- a `.myapprc.json`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, or `.myapprc.cjs` file
24- a `myapprc`, `myapprc.json`, `myapprc.yaml`, `myapprc.yml`, `myapprc.js` or `myapprc.cjs` file inside a `.config` subdirectory`
25- a `myapp.config.js` or `myapp.config.cjs` CommonJS module exporting an object
26
27Cosmiconfig continues to search up the directory tree, checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory).
28
29## Table of contents
30
31- [Installation](#installation)
32- [Usage](#usage)
33- [Result](#result)
34- [Asynchronous API](#asynchronous-api)
35 - [cosmiconfig()](#cosmiconfig-1)
36 - [explorer.search()](#explorersearch)
37 - [explorer.load()](#explorerload)
38 - [explorer.clearLoadCache()](#explorerclearloadcache)
39 - [explorer.clearSearchCache()](#explorerclearsearchcache)
40 - [explorer.clearCaches()](#explorerclearcaches)
41- [Synchronous API](#synchronous-api)
42 - [cosmiconfigSync()](#cosmiconfigsync)
43 - [explorerSync.search()](#explorersyncsearch)
44 - [explorerSync.load()](#explorersyncload)
45 - [explorerSync.clearLoadCache()](#explorersyncclearloadcache)
46 - [explorerSync.clearSearchCache()](#explorersyncclearsearchcache)
47 - [explorerSync.clearCaches()](#explorersyncclearcaches)
48- [cosmiconfigOptions](#cosmiconfigoptions)
49 - [searchPlaces](#searchplaces)
50 - [loaders](#loaders)
51 - [packageProp](#packageprop)
52 - [stopDir](#stopdir)
53 - [cache](#cache)
54 - [transform](#transform)
55 - [ignoreEmptySearchPlaces](#ignoreemptysearchplaces)
56- [Caching](#caching)
57- [Differences from rc](#differences-from-rc)
58- [Contributing & Development](#contributing--development)
59
60## Installation
61
62```
63npm install cosmiconfig
64```
65
66Tested in Node 10+.
67
68## Usage
69
70Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
71
72```js
73const { cosmiconfig, cosmiconfigSync } = require('cosmiconfig');
74// ...
75const explorer = cosmiconfig(moduleName);
76
77// Search for a configuration by walking up directories.
78// See documentation for search, below.
79explorer.search()
80 .then((result) => {
81 // result.config is the parsed configuration object.
82 // result.filepath is the path to the config file that was found.
83 // result.isEmpty is true if there was nothing to parse in the config file.
84 })
85 .catch((error) => {
86 // Do something constructive.
87 });
88
89// Load a configuration directly when you know where it should be.
90// The result object is the same as for search.
91// See documentation for load, below.
92explorer.load(pathToConfig).then(..);
93
94// You can also search and load synchronously.
95const explorerSync = cosmiconfigSync(moduleName);
96
97const searchedFor = explorerSync.search();
98const loaded = explorerSync.load(pathToConfig);
99```
100
101## Result
102
103The result object you get from `search` or `load` has the following properties:
104
105- **config:** The parsed configuration object. `undefined` if the file is empty.
106- **filepath:** The path to the configuration file that was found.
107- **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty.
108
109## Asynchronous API
110
111### cosmiconfig()
112
113```js
114const { cosmiconfig } = require('cosmiconfig');
115const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
116```
117
118Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
119
120#### moduleName
121
122Type: `string`. **Required.**
123
124Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`].
125
126If your [`searchPlaces`] value will include files, as it does by default (e.g. `${moduleName}rc`), your `moduleName` must consist of characters allowed in filenames. That means you should not copy scoped package names, such as `@my-org/my-package`, directly into `moduleName`.
127
128**[`cosmiconfigOptions`] are documented below.**
129You may not need them, and should first read about the functions you'll use.
130
131### explorer.search()
132
133```js
134explorer.search([searchFrom]).then(result => {..})
135```
136
137Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found.
138
139You can do the same thing synchronously with [`explorerSync.search()`].
140
141Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`.
142Here's how your default [`search()`] will work:
143
144- Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places:
145 1. A `goldengrahams` property in a `package.json` file.
146 2. A `.goldengrahamsrc` file with JSON or YAML syntax.
147 3. A `.goldengrahamsrc.json`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, or `.goldengrahamsrc.cjs` file.
148 4. A `goldengrahamsrc`, `goldengrahamsrc.json`, `goldengrahamsrc.yaml`, `goldengrahamsrc.yml`, `goldengrahamsrc.js`, or `goldengrahamsrc.cjs` file in the `.config` subdirectory.
149 5. A `goldengrahams.config.js` or `goldengrahams.config.cjs` CommonJS module exporting the object.
150- If none of those searches reveal a configuration object, move up one directory level and try again.
151 So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.
152- Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]).
153- If at any point a parsable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`explorerSync.search()`], the [result] is returned).
154- If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`explorerSync.search()`], `null` is returned).
155- If a configuration object is found *but is malformed* (causing a parsing error), the [`search()`] Promise rejects with that error (so you should `.catch()` it). (Or, with [`explorerSync.search()`], the error is thrown.)
156
157**If you know exactly where your configuration file should be, you can use [`load()`], instead.**
158
159**The search process is highly customizable.**
160Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them.
161
162#### searchFrom
163
164Type: `string`.
165Default: `process.cwd()`.
166
167A filename.
168[`search()`] will start its search here.
169
170If the value is a directory, that's where the search starts.
171If it's a file, the search starts in that file's directory.
172
173### explorer.load()
174
175```js
176explorer.load(loadPath).then(result => {..})
177```
178
179Loads a configuration file. Returns a Promise that resolves with a [result] or rejects with an error (if the file does not exist or cannot be loaded).
180
181Use `load` if you already know where the configuration file is and you just need to load it.
182
183```js
184explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
185```
186
187If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`].
188
189You can do the same thing synchronously with [`explorerSync.load()`].
190
191### explorer.clearLoadCache()
192
193Clears the cache used in [`load()`].
194
195### explorer.clearSearchCache()
196
197Clears the cache used in [`search()`].
198
199### explorer.clearCaches()
200
201Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
202
203## Synchronous API
204
205### cosmiconfigSync()
206
207```js
208const { cosmiconfigSync } = require('cosmiconfig');
209const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
210```
211
212Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
213
214See [`cosmiconfig()`].
215
216### explorerSync.search()
217
218```js
219const result = explorerSync.search([searchFrom]);
220```
221
222Synchronous version of [`explorer.search()`].
223
224Returns a [result] or `null`.
225
226### explorerSync.load()
227
228```js
229const result = explorerSync.load(loadPath);
230```
231
232Synchronous version of [`explorer.load()`].
233
234Returns a [result].
235
236### explorerSync.clearLoadCache()
237
238Clears the cache used in [`load()`].
239
240### explorerSync.clearSearchCache()
241
242Clears the cache used in [`search()`].
243
244### explorerSync.clearCaches()
245
246Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
247
248## cosmiconfigOptions
249
250Type: `Object`.
251
252Possible options are documented below.
253
254### searchPlaces
255
256Type: `Array<string>`.
257Default: See below.
258
259An array of places that [`search()`] will check in each directory as it moves up the directory tree.
260Each place is relative to the directory being searched, and the places are checked in the specified order.
261
262**Default `searchPlaces`:**
263
264```js
265[
266 'package.json',
267 `.${moduleName}rc`,
268 `.${moduleName}rc.json`,
269 `.${moduleName}rc.yaml`,
270 `.${moduleName}rc.yml`,
271 `.${moduleName}rc.js`,
272 `.${moduleName}rc.cjs`,
273 `.config/${moduleName}rc`,
274 `.config/${moduleName}rc.json`,
275 `.config/${moduleName}rc.yaml`,
276 `.config/${moduleName}rc.yml`,
277 `.config/${moduleName}rc.js`,
278 `.config/${moduleName}rc.cjs`,
279 `${moduleName}.config.js`,
280 `${moduleName}.config.cjs`,
281]
282```
283
284Create your own array to search more, fewer, or altogether different places.
285
286Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension.
287(Common extensions are covered by default loaders.)
288Read more about [`loaders`] below.
289
290`package.json` is a special value: When it is included in `searchPlaces`, Cosmiconfig will always parse it as JSON and load a property within it, not the whole file.
291That property is defined with the [`packageProp`] option, and defaults to your module name.
292
293Examples, with a module named `porgy`:
294
295```js
296// Disallow extensions on rc files:
297[
298 'package.json',
299 '.porgyrc',
300 'porgy.config.js'
301]
302
303// ESLint searches for configuration in these places:
304[
305 '.eslintrc.js',
306 '.eslintrc.yaml',
307 '.eslintrc.yml',
308 '.eslintrc.json',
309 '.eslintrc',
310 'package.json'
311]
312
313// Babel looks in fewer places:
314[
315 'package.json',
316 '.babelrc'
317]
318
319// Maybe you want to look for a wide variety of JS flavors:
320[
321 'porgy.config.js',
322 'porgy.config.mjs',
323 'porgy.config.ts',
324 'porgy.config.coffee'
325]
326// ^^ You will need to designate custom loaders to tell
327// Cosmiconfig how to handle these special JS flavors.
328
329// Look within a .config/ subdirectory of every searched directory:
330[
331 'package.json',
332 '.porgyrc',
333 '.config/.porgyrc',
334 '.porgyrc.json',
335 '.config/.porgyrc.json'
336]
337```
338
339### loaders
340
341Type: `Object`.
342Default: See below.
343
344An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
345
346Cosmiconfig exposes its default loaders on a named export `defaultLoaders`.
347
348**Default `loaders`:**
349
350```js
351const { defaultLoaders } = require('cosmiconfig');
352
353console.log(Object.entries(defaultLoaders))
354// [
355// [ '.cjs', [Function: loadJs] ],
356// [ '.js', [Function: loadJs] ],
357// [ '.json', [Function: loadJson] ],
358// [ '.yaml', [Function: loadYaml] ],
359// [ '.yml', [Function: loadYaml] ],
360// [ 'noExt', [Function: loadYaml] ]
361// ]
362```
363
364(YAML is a superset of JSON; which means YAML parsers can parse JSON; which is how extensionless files can be either YAML *or* JSON with only one parser.)
365
366**If you provide a `loaders` object, your object will be *merged* with the defaults.**
367So you can override one or two without having to override them all.
368
369**Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.myapprc`.
370
371**Values in `loaders`** are a loader function (described below) whose values are loader functions.
372
373**The most common use case for custom loaders value is to load extensionless `rc` files as strict JSON**, instead of JSON *or* YAML (the default).
374To accomplish that, provide the following `loaders` value:
375
376```js
377{
378 noExt: defaultLoaders['.json']
379}
380```
381
382If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function or use one from NPM if it exists.
383
384**Third-party loaders:**
385
386- [cosmiconfig-typescript-loader](https://github.com/codex-/cosmiconfig-typescript-loader)
387
388**Use cases for custom loader function:**
389
390- Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
391- Allow ES2015 modules from `.mjs` configuration files.
392- Parse JS files with Babel before deriving the configuration.
393
394**Custom loader functions** have the following signature:
395
396```js
397// Sync
398(filepath: string, content: string) => Object | null
399
400// Async
401(filepath: string, content: string) => Object | null | Promise<Object | null>
402```
403
404Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
405Do whatever you need to, and return either a configuration object or `null` (or, for async-only loaders, a Promise that resolves with one of those).
406`null` indicates that no real configuration was found and the search should continue.
407
408A few things to note:
409
410- If you use a custom loader, be aware of whether it's sync or async: you cannot use async customer loaders with the sync API ([`cosmiconfigSync()`]).
411- **Special JS syntax can also be handled by using a `require` hook**, because `defaultLoaders['.js']` just uses `require`.
412 Whether you use custom loaders or a `require` hook is up to you.
413
414Examples:
415
416```js
417// Allow JSON5 syntax:
418{
419 '.json': json5Loader
420}
421
422// Allow a special configuration syntax of your own creation:
423{
424 '.special': specialLoader
425}
426
427// Allow many flavors of JS, using custom loaders:
428{
429 '.mjs': esmLoader,
430 '.ts': typeScriptLoader,
431 '.coffee': coffeeScriptLoader
432}
433
434// Allow many flavors of JS but rely on require hooks:
435{
436 '.mjs': defaultLoaders['.js'],
437 '.ts': defaultLoaders['.js'],
438 '.coffee': defaultLoaders['.js']
439}
440```
441
442### packageProp
443
444Type: `string | Array<string>`.
445Default: `` `${moduleName}` ``.
446
447Name of the property in `package.json` to look for.
448
449Use a period-delimited string or an array of strings to describe a path to nested properties.
450
451For example, the value `'configs.myPackage'` or `['configs', 'myPackage']` will get you the `"myPackage"` value in a `package.json` like this:
452
453```json
454{
455 "configs": {
456 "myPackage": {..}
457 }
458}
459```
460
461If nested property names within the path include periods, you need to use an array of strings. For example, the value `['configs', 'foo.bar', 'baz']` will get you the `"baz"` value in a `package.json` like this:
462
463```json
464{
465 "configs": {
466 "foo.bar": {
467 "baz": {..}
468 }
469 }
470}
471```
472
473If a string includes period but corresponds to a top-level property name, it will not be interpreted as a period-delimited path. For example, the value `'one.two'` will get you the `"three"` value in a `package.json` like this:
474
475```json
476{
477 "one.two": "three",
478 "one": {
479 "two": "four"
480 }
481}
482```
483
484### stopDir
485
486Type: `string`.
487Default: Absolute path to your home directory.
488
489Directory where the search will stop.
490
491### cache
492
493Type: `boolean`.
494Default: `true`.
495
496If `false`, no caches will be used.
497Read more about ["Caching"](#caching) below.
498
499### transform
500
501Type: `(Result) => Promise<Result> | Result`.
502
503A function that transforms the parsed configuration. Receives the [result].
504
505If using [`search()`] or [`load()`] \(which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result.
506If using `cosmiconfigSync`, [`search()`] or [`load()`], the function must be synchronous and return the transformed result.
507
508The reason you might use this option — instead of simply applying your transform function some other way — is that *the transformed result will be cached*. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is searched or loaded.
509
510### ignoreEmptySearchPlaces
511
512Type: `boolean`.
513Default: `true`.
514
515By default, if [`search()`] encounters an empty file (containing nothing but whitespace) in one of the [`searchPlaces`], it will ignore the empty file and move on.
516If you'd like to load empty configuration files, instead, set this option to `false`.
517
518Why might you want to load empty configuration files?
519If you want to throw an error, or if an empty configuration file means something to your program.
520
521## Caching
522
523As of v2, cosmiconfig uses caching to reduce the need for repetitious reading of the filesystem or expensive transforms. Every new cosmiconfig instance (created with `cosmiconfig()`) has its own caches.
524
525To avoid or work around caching, you can do the following:
526
527- Set the `cosmiconfig` option [`cache`] to `false`.
528- Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`].
529- Create separate instances of cosmiconfig (separate "explorers").
530
531## Differences from [rc](https://github.com/dominictarr/rc)
532
533[rc](https://github.com/dominictarr/rc) serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
534
535- Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
536- Built-in support for JSON, YAML, and CommonJS formats.
537- Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
538- Options.
539- Asynchronous by default (though can be run synchronously).
540
541## Contributing & Development
542
543Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
544
545And please do participate!
546
547[result]: #result
548
549[`load()`]: #explorerload
550
551[`search()`]: #explorersearch
552
553[`clearloadcache()`]: #explorerclearloadcache
554
555[`clearsearchcache()`]: #explorerclearsearchcache
556
557[`cosmiconfig()`]: #cosmiconfig
558
559[`cosmiconfigSync()`]: #cosmiconfigsync
560
561[`clearcaches()`]: #explorerclearcaches
562
563[`packageprop`]: #packageprop
564
565[`cache`]: #cache
566
567[`stopdir`]: #stopdir
568
569[`searchplaces`]: #searchplaces
570
571[`loaders`]: #loaders
572
573[`cosmiconfigoptions`]: #cosmiconfigoptions
574
575[`explorerSync.search()`]: #explorersyncsearch
576
577[`explorerSync.load()`]: #explorersyncload
578
579[`explorer.search()`]: #explorersearch
580
581[`explorer.load()`]: #explorerload
Note: See TracBrowser for help on using the repository browser.