UNPKG

17.1 kBMarkdownView Raw
1# cosmiconfig
2
3[![Build Status](https://img.shields.io/travis/davidtheclark/cosmiconfig/master.svg?label=unix%20build)](https://travis-ci.org/davidtheclark/cosmiconfig) [![Build status](https://img.shields.io/appveyor/ci/davidtheclark/cosmiconfig/master.svg?label=windows%20build)](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/master)
4
5Cosmiconfig searches for and loads configuration for your program.
6
7It features smart defaults based on conventional expectations in the JavaScript ecosystem.
8But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
9
10By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following:
11
12- a `package.json` property
13- a JSON or YAML, extensionless "rc file"
14- an "rc file" with the extensions `.json`, `.yaml`, or `.yml`.
15- a `.config.js` CommonJS module
16
17For example, if your module's name is "soursocks", cosmiconfig will search for configuration in the following places:
18
19- a `soursocks` property in `package.json` (anywhere up the directory tree)
20- a `.soursocksrc` file in JSON or YAML format (anywhere up the directory tree)
21- a `.soursocksrc.json` file
22- a `.soursocksrc.yaml` or `.soursocksrc.yml` file
23- a `soursocks.config.js` file exporting a JS object (anywhere up the directory tree)
24
25Cosmiconfig 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).
26
27👀 **Looking for the v4 docs?**
28v5 involves significant revisions to Cosmiconfig's API, allowing for much greater flexibility and clarifying some things.
29If you have trouble switching from v4 to v5, please file an issue.
30If you are still using v4, those v4 docs are available [in the `4.0.0` tag](https://github.com/davidtheclark/cosmiconfig/tree/4.0.0).
31
32## Table of contents
33
34- [Installation](#installation)
35- [Usage](#usage)
36- [Result](#result)
37- [cosmiconfig()](#cosmiconfig-1)
38 - [moduleName](#modulename)
39- [explorer.search()](#explorersearch)
40 - [searchFrom](#searchfrom)
41- [explorer.searchSync()](#explorersearchsync)
42- [explorer.load()](#explorerload)
43- [explorer.loadSync()](#explorerloadsync)
44- [explorer.clearLoadCache()](#explorerclearloadcache)
45- [explorer.clearSearchCache()](#explorerclearsearchcache)
46- [explorer.clearCaches()](#explorerclearcaches)
47- [cosmiconfigOptions](#cosmiconfigoptions)
48 - [searchPlaces](#searchplaces)
49 - [loaders](#loaders)
50 - [packageProp](#packageprop)
51 - [stopDir](#stopdir)
52 - [cache](#cache)
53 - [transform](#transform)
54 - [ignoreEmptySearchPlaces](#ignoreemptysearchplaces)
55- [Caching](#caching)
56- [Differences from rc](#differences-from-rc)
57- [Contributing & Development](#contributing--development)
58
59## Installation
60
61```
62npm install cosmiconfig
63```
64
65Tested in Node 4+.
66
67## Usage
68
69Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
70
71```js
72const cosmiconfig = require('cosmiconfig');
73// ...
74const explorer = cosmiconfig(moduleName);
75
76// Search for a configuration by walking up directories.
77// See documentation for search, below.
78explorer.search()
79 .then((result) => {
80 // result.config is the parsed configuration object.
81 // result.filepath is the path to the config file that was found.
82 // result.isEmpty is true if there was nothing to parse in the config file.
83 })
84 .catch((error) => {
85 // Do something constructive.
86 });
87
88// Load a configuration directly when you know where it should be.
89// The result object is the same as for search.
90// See documentation for load, below.
91explorer.load(pathToConfig).then(..);
92
93// You can also search and load synchronously.
94const searchedFor = explorer.searchSync();
95const loaded = explorer.loadSync(pathToConfig);
96```
97
98## Result
99
100The result object you get from `search` or `load` has the following properties:
101
102- **config:** The parsed configuration object. `undefined` if the file is empty.
103- **filepath:** The path to the configuration file that was found.
104- **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty.
105
106## cosmiconfig()
107
108```js
109const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
110```
111
112Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
113
114### moduleName
115
116Type: `string`. **Required.**
117
118Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`].
119
120**[`cosmiconfigOptions`] are documented below.**
121You may not need them, and should first read about the functions you'll use.
122
123## explorer.search()
124
125```js
126explorer.search([searchFrom]).then(result => {..})
127```
128
129Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found.
130
131You can do the same thing synchronously with [`searchSync()`].
132
133Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`.
134Here's how your default [`search()`] will work:
135
136- Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places:
137 1. A `goldengrahams` property in a `package.json` file.
138 2. A `.goldengrahamsrc` file with JSON or YAML syntax.
139 3. A `.goldengrahamsrc.json` file.
140 4. A `.goldengrahamsrc.yaml` or `.goldengrahamsrc.yml` file.
141 5. A `goldengrahams.config.js` JS file exporting the object.
142- If none of those searches reveal a configuration object, move up one directory level and try again.
143 So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.
144- Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]).
145- If at any point a parseable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`searchSync()`], the [result] is returned).
146- If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`searchSync()`], `null` is returned).
147- 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 [`searchSync()`], the error is thrown.)
148
149**If you know exactly where your configuration file should be, you can use [`load()`], instead.**
150
151**The search process is highly customizable.**
152Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them.
153
154### searchFrom
155
156Type: `string`.
157Default: `process.cwd()`.
158
159A filename.
160[`search()`] will start its search here.
161
162If the value is a directory, that's where the search starts.
163If it's a file, the search starts in that file's directory.
164
165## explorer.searchSync()
166
167```js
168const result = explorer.search([searchFrom]);
169```
170
171Synchronous version of [`search()`].
172
173Returns a [result] or `null`.
174
175## explorer.load()
176
177```js
178explorer.load([loadPath]).then(result => {..})
179```
180
181Loads 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).
182
183Use `load` if you already know where the configuration file is and you just need to load it.
184
185```js
186explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
187```
188
189If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`].
190
191## explorer.loadSync()
192
193```js
194const result = explorer.load([loadPath]);
195```
196
197Synchronous version of [`load()`].
198
199Returns a [result].
200
201## explorer.clearLoadCache()
202
203Clears the cache used in [`load()`].
204
205## explorer.clearSearchCache()
206
207Clears the cache used in [`search()`].
208
209## explorer.clearCaches()
210
211Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
212
213## cosmiconfigOptions
214
215### searchPlaces
216
217Type: `Array<string>`.
218Default: See below.
219
220An array of places that [`search()`] will check in each directory as it moves up the directory tree.
221Each place is relative to the directory being searched, and the places are checked in the specified order.
222
223**Default `searchPlaces`:**
224
225```js
226[
227 'package.json',
228 `.${moduleName}rc`,
229 `.${moduleName}rc.json`,
230 `.${moduleName}rc.yaml`,
231 `.${moduleName}rc.yml`,
232 `${moduleName}.config.js`,
233]
234```
235
236Create your own array to search more, fewer, or altogether different places.
237
238Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension.
239(Common extensions are covered by default loaders.)
240Read more about [`loaders`] below.
241
242`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.
243That property is defined with the [`packageProp`] option, and defaults to your module name.
244
245Examples, with a module named `porgy`:
246
247```js
248// Disallow extensions on rc files:
249[
250 'package.json',
251 '.porgyrc',
252 'porgy.config.js'
253]
254
255// ESLint searches for configuration in these places:
256[
257 '.eslintrc.js',
258 '.eslintrc.yaml',
259 '.eslintrc.yml',
260 '.eslintrc.json',
261 '.eslintrc',
262 'package.json'
263]
264
265// Babel looks in fewer places:
266[
267 'package.json',
268 '.babelrc'
269]
270
271// Maybe you want to look for a wide variety of JS flavors:
272[
273 'porgy.config.js',
274 'porgy.config.mjs',
275 'porgy.config.ts',
276 'porgy.config.coffee'
277]
278// ^^ You will need to designate custom loaders to tell
279// Cosmiconfig how to handle these special JS flavors.
280
281// Look within a .config/ subdirectory of every searched directory:
282[
283 'package.json',
284 '.porgyrc',
285 '.config/.porgyrc',
286 '.porgyrc.json',
287 '.config/.porgyrc.json'
288]
289```
290
291### loaders
292
293Type: `Object`.
294Default: See below.
295
296An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
297
298Cosmiconfig exposes its default loaders for `.js`, `.json`, and `.yaml` as `cosmiconfig.loadJs`, `cosmiconfig.loadJson`, and `cosmiconfig.loadYaml`, respectively.
299
300**Default `loaders`:**
301
302```js
303{
304 '.json': cosmiconfig.loadJson,
305 '.yaml': cosmiconfig.loadYaml,
306 '.yml': cosmiconfig.loadYaml,
307 '.js': cosmiconfig.loadJs,
308 noExt: cosmiconfig.loadYaml
309}
310```
311
312(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.)
313
314**If you provide a `loaders` object, your object will be *merged* with the defaults.**
315So you can override one or two without having to override them all.
316
317**Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.soursocksrc`.
318
319**Values in `loaders`** are either a loader function (described below) or an object with `sync` and/or `async` properties, whose values are loader functions.
320
321**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).
322To accomplish that, provide the following `loaders` value:
323
324```js
325{
326 noExt: cosmiconfig.loadJson
327}
328```
329
330If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function.
331
332**Use cases for custom loader function:**
333
334- Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
335- Allow ES2015 modules from `.mjs` configuration files.
336- Parse JS files with Babel before deriving the configuration.
337
338**Custom loader functions** have the following signature:
339
340```js
341// Sync
342(filepath: string, content: string) => Object | null
343
344// Async
345(filepath: string, content: string) => Object | null | Promise<Object | null>
346```
347
348Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
349Do 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).
350`null` indicates that no real configuration was found and the search should continue.
351
352It's easiest if you make your custom loader function synchronous.
353Then it can be used regardless of whether you end up calling [`search()`] or [`searchSync()`], [`load()`] or [`loadSync()`].
354If you want or need to provide an async-only loader, you can do so by making the value of `loaders` an object with an `async` property whose value is the async loader.
355You can also add a `sync` property to designate a sync loader, if you want to use both async and sync search and load functions.
356
357If an extension has *only* an async loader but you try to use [`searchSync()`] or [`loadSync()`], an error will be thrown.
358
359Note that **special JS syntax can also be handled by using a `require` hook**, because `cosmiconfig.loadJs` just uses `require`.
360Whether you use custom loaders or a `require` hook is up to you.
361
362Examples:
363
364```js
365// Allow JSON5 syntax:
366{
367 '.json': json5Loader
368}
369
370// Allow XML, and treat sync and async separately:
371{
372 '.xml': { async: asyncXmlLoader, sync: syncXmlLoader }
373}
374
375// Allow a special configuration syntax of your own creation:
376{
377 '.special': specialLoader
378}
379
380// Allow many flavors of JS, using custom loaders:
381{
382 '.mjs': esmLoader,
383 '.ts': typeScriptLoader,
384 '.coffee': coffeeScriptLoader
385}
386
387// Allow many flavors of JS but rely on require hooks:
388{
389 '.mjs': cosmiconfig.loadJs,
390 '.ts': cosmiconfig.loadJs,
391 '.coffee': cosmiconfig.loadJs
392}
393```
394
395### packageProp
396
397Type: `string`.
398Default: `` `${moduleName}` ``.
399
400Name of the property in `package.json` to look for.
401
402### stopDir
403
404Type: `string`.
405Default: Absolute path to your home directory.
406
407Directory where the search will stop.
408
409### cache
410
411Type: `boolean`.
412Default: `true`.
413
414If `false`, no caches will be used.
415Read more about ["Caching"](#caching) below.
416
417### transform
418
419Type: `(Result) => Promise<Result> | Result`.
420
421A function that transforms the parsed configuration. Receives the [result].
422
423If 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.
424If using [`searchSync()`] or [`loadSync()`], the function must be synchronous and return the transformed result.
425
426The 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.
427
428### ignoreEmptySearchPlaces
429
430Type: `boolean`.
431Default: `true`.
432
433By 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.
434If you'd like to load empty configuration files, instead, set this option to `false`.
435
436Why might you want to load empty configuration files?
437If you want to throw an error, or if an empty configuration file means something to your program.
438
439## Caching
440
441As 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.
442
443To avoid or work around caching, you can do the following:
444
445- Set the `cosmiconfig` option [`cache`] to `false`.
446- Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`].
447- Create separate instances of cosmiconfig (separate "explorers").
448
449## Differences from [rc](https://github.com/dominictarr/rc)
450
451[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:
452
453- Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
454- Built-in support for JSON, YAML, and CommonJS formats.
455- Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
456- Options.
457- Asynchronous by default (though can be run synchronously).
458
459## Contributing & Development
460
461Please 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.
462
463And please do participate!
464
465[result]: #result
466
467[`load()`]: #explorerload
468
469[`loadsync()`]: #explorerloadsync
470
471[`search()`]: #explorersearch
472
473[`searchsync()`]: #explorersearchsync
474
475[`clearloadcache()`]: #explorerclearloadcache
476
477[`clearsearchcache()`]: #explorerclearsearchcache
478
479[`clearcaches()`]: #explorerclearcaches
480
481[`packageprop`]: #packageprop
482
483[`cache`]: #cache
484
485[`stopdir`]: #stopdir
486
487[`searchplaces`]: #searchplaces
488
489[`loaders`]: #loaders
490
491[`cosmiconfigoptions`]: #cosmiconfigoptions