1 | # cosmiconfig
|
2 |
|
3 | [](https://codecov.io/gh/cosmiconfig/cosmiconfig)
|
4 |
|
5 | Cosmiconfig searches for and loads configuration for your program.
|
6 |
|
7 | It features smart defaults based on conventional expectations in the JavaScript ecosystem.
|
8 | But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
|
9 |
|
10 | By 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`, `.yml`, `.js`, `.ts`, `.mjs`, or `.cjs`
|
15 | - any of the above two inside a `.config` subdirectory
|
16 | - a `.config.js`, `.config.ts`, `.config.mjs`, or `.config.cjs` file
|
17 |
|
18 | For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
|
19 |
|
20 | - a `myapp` property in `package.json`
|
21 | - a `.myapprc` file in JSON or YAML format
|
22 | - a `.myapprc.json`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, `.myapprc.ts`, `.myapprc.mjs`, or `.myapprc.cjs` file
|
23 | - a `myapprc`, `myapprc.json`, `myapprc.yaml`, `myapprc.yml`, `myapprc.js`, `myapprc.ts` or `myapprc.cjs` file inside a `.config` subdirectory
|
24 | - a `myapp.config.js`, `myapp.config.ts`, `myapp.config.mjs`, or `myapp.config.cjs` file
|
25 |
|
26 | Cosmiconfig 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).
|
27 |
|
28 | ## Table of contents
|
29 |
|
30 | - [Installation](#installation)
|
31 | - [Usage for tooling developers](#usage-for-tooling-developers)
|
32 | - [Result](#result)
|
33 | - [Asynchronous API](#asynchronous-api)
|
34 | - [cosmiconfig()](#cosmiconfig-1)
|
35 | - [explorer.search()](#explorersearch)
|
36 | - [explorer.load()](#explorerload)
|
37 | - [explorer.clearLoadCache()](#explorerclearloadcache)
|
38 | - [explorer.clearSearchCache()](#explorerclearsearchcache)
|
39 | - [explorer.clearCaches()](#explorerclearcaches)
|
40 | - [Synchronous API](#synchronous-api)
|
41 | - [cosmiconfigSync()](#cosmiconfigsync)
|
42 | - [explorerSync.search()](#explorersyncsearch)
|
43 | - [explorerSync.load()](#explorersyncload)
|
44 | - [explorerSync.clearLoadCache()](#explorersyncclearloadcache)
|
45 | - [explorerSync.clearSearchCache()](#explorersyncclearsearchcache)
|
46 | - [explorerSync.clearCaches()](#explorersyncclearcaches)
|
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 | - [Loading JS modules](#loading-js-modules)
|
56 | - [Caching](#caching)
|
57 | - [Differences from rc](#differences-from-rc)
|
58 | - [Usage for end users](#usage-for-end-users)
|
59 | - [Contributing & Development](#contributing--development)
|
60 |
|
61 | ## Installation
|
62 |
|
63 | ```
|
64 | npm install cosmiconfig
|
65 | ```
|
66 |
|
67 | Tested in Node 14+.
|
68 |
|
69 | ## Usage for tooling developers
|
70 |
|
71 | *If you are an end user (i.e. a user of a tool that uses cosmiconfig, like `prettier` or `stylelint`),
|
72 | you can skip down to [the end user section](#usage-for-end-users).*
|
73 |
|
74 | Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
|
75 |
|
76 | ```js
|
77 | const { cosmiconfig, cosmiconfigSync } = require('cosmiconfig');
|
78 | // ...
|
79 | const explorer = cosmiconfig(moduleName);
|
80 |
|
81 | // Search for a configuration by walking up directories.
|
82 | // See documentation for search, below.
|
83 | explorer.search()
|
84 | .then((result) => {
|
85 | // result.config is the parsed configuration object.
|
86 | // result.filepath is the path to the config file that was found.
|
87 | // result.isEmpty is true if there was nothing to parse in the config file.
|
88 | })
|
89 | .catch((error) => {
|
90 | // Do something constructive.
|
91 | });
|
92 |
|
93 | // Load a configuration directly when you know where it should be.
|
94 | // The result object is the same as for search.
|
95 | // See documentation for load, below.
|
96 | explorer.load(pathToConfig).then(..);
|
97 |
|
98 | // You can also search and load synchronously.
|
99 | const explorerSync = cosmiconfigSync(moduleName);
|
100 |
|
101 | const searchedFor = explorerSync.search();
|
102 | const loaded = explorerSync.load(pathToConfig);
|
103 | ```
|
104 |
|
105 | ## Result
|
106 |
|
107 | The result object you get from `search` or `load` has the following properties:
|
108 |
|
109 | - **config:** The parsed configuration object. `undefined` if the file is empty.
|
110 | - **filepath:** The path to the configuration file that was found.
|
111 | - **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty.
|
112 |
|
113 | ## Asynchronous API
|
114 |
|
115 | ### cosmiconfig()
|
116 |
|
117 | ```js
|
118 | const { cosmiconfig } = require('cosmiconfig');
|
119 | const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
|
120 | ```
|
121 |
|
122 | Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
|
123 |
|
124 | #### moduleName
|
125 |
|
126 | Type: `string`. **Required.**
|
127 |
|
128 | Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`].
|
129 |
|
130 | If 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`.
|
131 |
|
132 | **[`cosmiconfigOptions`] are documented below.**
|
133 | You may not need them, and should first read about the functions you'll use.
|
134 |
|
135 | ### explorer.search()
|
136 |
|
137 | ```js
|
138 | explorer.search([searchFrom]).then(result => {..})
|
139 | ```
|
140 |
|
141 | Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found.
|
142 |
|
143 | You can do the same thing synchronously with [`explorerSync.search()`].
|
144 |
|
145 | Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`.
|
146 | Here's how your default [`search()`] will work:
|
147 |
|
148 | - Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places:
|
149 | 1. A `goldengrahams` property in a `package.json` file.
|
150 | 2. A `.goldengrahamsrc` file with JSON or YAML syntax.
|
151 | 3. A `.goldengrahamsrc.json`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, `.goldengrahamsrc.ts`, or `.goldengrahamsrc.cjs` file. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
|
152 | 4. A `goldengrahamsrc`, `goldengrahamsrc.json`, `goldengrahamsrc.yaml`, `goldengrahamsrc.yml`, `goldengrahamsrc.js`, `goldengrahamsrc.ts`, or `goldengrahamsrc.cjs` file in the `.config` subdirectory.
|
153 | 5. A `goldengrahams.config.js`, `goldengrahams.config.ts`, `goldengrahams.config.mjs`, or `goldengrahams.config.cjs` file. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
|
154 | - If none of those searches reveal a configuration object, move up one directory level and try again.
|
155 | So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.
|
156 | - Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]).
|
157 | - For JS files,
|
158 | - If at any point a parsable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`explorerSync.search()`], the [result] is returned).
|
159 | - If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`explorerSync.search()`], `null` is returned).
|
160 | - 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.)
|
161 |
|
162 | **If you know exactly where your configuration file should be, you can use [`load()`], instead.**
|
163 |
|
164 | **The search process is highly customizable.**
|
165 | Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them.
|
166 |
|
167 | #### searchFrom
|
168 |
|
169 | Type: `string`.
|
170 | Default: `process.cwd()`.
|
171 |
|
172 | A filename.
|
173 | [`search()`] will start its search here.
|
174 |
|
175 | If the value is a directory, that's where the search starts.
|
176 | If it's a file, the search starts in that file's directory.
|
177 |
|
178 | ### explorer.load()
|
179 |
|
180 | ```js
|
181 | explorer.load(loadPath).then(result => {..})
|
182 | ```
|
183 |
|
184 | Loads 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).
|
185 |
|
186 | Use `load` if you already know where the configuration file is and you just need to load it.
|
187 |
|
188 | ```js
|
189 | explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
|
190 | ```
|
191 |
|
192 | If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`].
|
193 |
|
194 | You can do the same thing synchronously with [`explorerSync.load()`].
|
195 |
|
196 | ### explorer.clearLoadCache()
|
197 |
|
198 | Clears the cache used in [`load()`].
|
199 |
|
200 | ### explorer.clearSearchCache()
|
201 |
|
202 | Clears the cache used in [`search()`].
|
203 |
|
204 | ### explorer.clearCaches()
|
205 |
|
206 | Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
|
207 |
|
208 | ## Synchronous API
|
209 |
|
210 | ### cosmiconfigSync()
|
211 |
|
212 | ```js
|
213 | const { cosmiconfigSync } = require('cosmiconfig');
|
214 | const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
|
215 | ```
|
216 |
|
217 | Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
|
218 |
|
219 | See [`cosmiconfig()`](#cosmiconfig-1).
|
220 |
|
221 | ### explorerSync.search()
|
222 |
|
223 | ```js
|
224 | const result = explorerSync.search([searchFrom]);
|
225 | ```
|
226 |
|
227 | Synchronous version of [`explorer.search()`].
|
228 |
|
229 | Returns a [result] or `null`.
|
230 |
|
231 | ### explorerSync.load()
|
232 |
|
233 | ```js
|
234 | const result = explorerSync.load(loadPath);
|
235 | ```
|
236 |
|
237 | Synchronous version of [`explorer.load()`].
|
238 |
|
239 | Returns a [result].
|
240 |
|
241 | ### explorerSync.clearLoadCache()
|
242 |
|
243 | Clears the cache used in [`load()`].
|
244 |
|
245 | ### explorerSync.clearSearchCache()
|
246 |
|
247 | Clears the cache used in [`search()`].
|
248 |
|
249 | ### explorerSync.clearCaches()
|
250 |
|
251 | Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
|
252 |
|
253 | ## cosmiconfigOptions
|
254 |
|
255 | Type: `Object`.
|
256 |
|
257 | Possible options are documented below.
|
258 |
|
259 | ### searchPlaces
|
260 |
|
261 | Type: `Array<string>`.
|
262 | Default: See below.
|
263 |
|
264 | An array of places that [`search()`] will check in each directory as it moves up the directory tree.
|
265 | Each place is relative to the directory being searched, and the places are checked in the specified order.
|
266 |
|
267 | **Default `searchPlaces`:**
|
268 |
|
269 | For the [asynchronous API](#asynchronous-api), these are the default `searchPlaces`:
|
270 |
|
271 | ```js
|
272 | [
|
273 | 'package.json',
|
274 | `.${moduleName}rc`,
|
275 | `.${moduleName}rc.json`,
|
276 | `.${moduleName}rc.yaml`,
|
277 | `.${moduleName}rc.yml`,
|
278 | `.${moduleName}rc.js`,
|
279 | `.${moduleName}rc.ts`,
|
280 | `.${moduleName}rc.mjs`,
|
281 | `.${moduleName}rc.cjs`,
|
282 | `.config/${moduleName}rc`,
|
283 | `.config/${moduleName}rc.json`,
|
284 | `.config/${moduleName}rc.yaml`,
|
285 | `.config/${moduleName}rc.yml`,
|
286 | `.config/${moduleName}rc.js`,
|
287 | `.config/${moduleName}rc.ts`,
|
288 | `.config/${moduleName}rc.cjs`,
|
289 | `${moduleName}.config.js`,
|
290 | `${moduleName}.config.ts`,
|
291 | `${moduleName}.config.mjs`,
|
292 | `${moduleName}.config.cjs`,
|
293 | ];
|
294 | ```
|
295 |
|
296 | For the [synchronous API](#synchronous-api), the only difference is that `.mjs` files are not included. See ["Loading JS modules"] for more information.
|
297 |
|
298 | Create your own array to search more, fewer, or altogether different places.
|
299 |
|
300 | Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension.
|
301 | (Common extensions are covered by default loaders.)
|
302 | Read more about [`loaders`] below.
|
303 |
|
304 | `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.
|
305 | That property is defined with the [`packageProp`] option, and defaults to your module name.
|
306 |
|
307 | Examples, with a module named `porgy`:
|
308 |
|
309 | ```js
|
310 | // Disallow extensions on rc files:
|
311 | ['package.json', '.porgyrc', 'porgy.config.js'][
|
312 | // Limit the options dramatically:
|
313 | ('package.json', '.porgyrc')
|
314 | ][
|
315 | // Maybe you want to look for a wide variety of JS flavors:
|
316 | ('porgy.config.js',
|
317 | 'porgy.config.mjs',
|
318 | 'porgy.config.ts',
|
319 | 'porgy.config.coffee')
|
320 | ][
|
321 | // ^^ You will need to designate custom loaders to tell
|
322 | // Cosmiconfig how to handle `.ts` and `.coffee` files.
|
323 |
|
324 | // Look within a .config/ subdirectory of every searched directory:
|
325 | ('package.json',
|
326 | '.porgyrc',
|
327 | '.config/.porgyrc',
|
328 | '.porgyrc.json',
|
329 | '.config/.porgyrc.json')
|
330 | ];
|
331 | ```
|
332 |
|
333 | ### loaders
|
334 |
|
335 | Type: `Object`.
|
336 | Default: See below.
|
337 |
|
338 | An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
|
339 |
|
340 | Cosmiconfig exposes its default loaders on the named export `defaultLoaders` and `defaultLoadersSync`.
|
341 |
|
342 | **Default `loaders`:**
|
343 |
|
344 | ```js
|
345 | const { defaultLoaders, defaultLoadersSync } = require('cosmiconfig');
|
346 |
|
347 | console.log(Object.entries(defaultLoaders));
|
348 | // [
|
349 | // [ '.mjs', [Function: loadJs] ],
|
350 | // [ '.cjs', [Function: loadJs] ],
|
351 | // [ '.js', [Function: loadJs] ],
|
352 | // [ '.ts', [Function: loadTs] ],
|
353 | // [ '.json', [Function: loadJson] ],
|
354 | // [ '.yaml', [Function: loadYaml] ],
|
355 | // [ '.yml', [Function: loadYaml] ],
|
356 | // [ 'noExt', [Function: loadYaml] ]
|
357 | // ]
|
358 |
|
359 | console.log(Object.entries(defaultLoadersSync));
|
360 | // [
|
361 | // [ '.cjs', [Function: loadJsSync] ],
|
362 | // [ '.js', [Function: loadJsSync] ],
|
363 | // [ '.ts', [Function: loadTsSync] ],
|
364 | // [ '.json', [Function: loadJson] ],
|
365 | // [ '.yaml', [Function: loadYaml] ],
|
366 | // [ '.yml', [Function: loadYaml] ],
|
367 | // [ 'noExt', [Function: loadYaml] ]
|
368 | // ]
|
369 | ```
|
370 |
|
371 | (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.)
|
372 |
|
373 | **If you provide a `loaders` object, your object will be *merged* with the defaults.**
|
374 | So you can override one or two without having to override them all.
|
375 |
|
376 | **Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.myapprc`.
|
377 |
|
378 | **Values in `loaders`** are a loader function (described below) whose values are loader functions.
|
379 |
|
380 | **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).
|
381 | To accomplish that, provide the following `loaders` value:
|
382 |
|
383 | ```js
|
384 | {
|
385 | noExt: defaultLoaders['.json'];
|
386 | }
|
387 | ```
|
388 |
|
389 | If 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.
|
390 |
|
391 | **Third-party loaders:**
|
392 |
|
393 | - [cosmiconfig-typescript-loader](https://github.com/codex-/cosmiconfig-typescript-loader)
|
394 |
|
395 | **Use cases for custom loader function:**
|
396 |
|
397 | - Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
|
398 | - Allow ES2015 modules from `.mjs` configuration files.
|
399 | - Parse JS files with Babel before deriving the configuration.
|
400 |
|
401 | **Custom loader functions** have the following signature:
|
402 |
|
403 | ```js
|
404 | // Sync
|
405 | (filepath: string, content: string) => Object | null
|
406 |
|
407 | // Async
|
408 | (filepath: string, content: string) => Object | null | Promise<Object | null>
|
409 | ```
|
410 |
|
411 | Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
|
412 | Do 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).
|
413 | `null` indicates that no real configuration was found and the search should continue.
|
414 |
|
415 | A few things to note:
|
416 |
|
417 | - 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()`]).
|
418 | - **Special JS syntax can also be handled by using a `require` hook**, because `defaultLoaders['.js']` just uses `require`.
|
419 | Whether you use custom loaders or a `require` hook is up to you.
|
420 |
|
421 | Examples:
|
422 |
|
423 | ```js
|
424 | // Allow JSON5 syntax:
|
425 | {
|
426 | '.json': json5Loader
|
427 | }
|
428 |
|
429 | // Allow a special configuration syntax of your own creation:
|
430 | {
|
431 | '.special': specialLoader
|
432 | }
|
433 |
|
434 | // Allow many flavors of JS, using custom loaders:
|
435 | {
|
436 | '.coffee': coffeeScriptLoader
|
437 | }
|
438 |
|
439 | // Allow many flavors of JS but rely on require hooks:
|
440 | {
|
441 | '.coffee': defaultLoaders['.js']
|
442 | }
|
443 | ```
|
444 |
|
445 | ### packageProp
|
446 |
|
447 | Type: `string | Array<string>`.
|
448 | Default: `` `${moduleName}` ``.
|
449 |
|
450 | Name of the property in `package.json` to look for.
|
451 |
|
452 | Use a period-delimited string or an array of strings to describe a path to nested properties.
|
453 |
|
454 | For example, the value `'configs.myPackage'` or `['configs', 'myPackage']` will get you the `"myPackage"` value in a `package.json` like this:
|
455 |
|
456 | ```json
|
457 | {
|
458 | "configs": {
|
459 | "myPackage": {..}
|
460 | }
|
461 | }
|
462 | ```
|
463 |
|
464 | If 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:
|
465 |
|
466 | ```json
|
467 | {
|
468 | "configs": {
|
469 | "foo.bar": {
|
470 | "baz": {..}
|
471 | }
|
472 | }
|
473 | }
|
474 | ```
|
475 |
|
476 | If 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:
|
477 |
|
478 | ```json
|
479 | {
|
480 | "one.two": "three",
|
481 | "one": {
|
482 | "two": "four"
|
483 | }
|
484 | }
|
485 | ```
|
486 |
|
487 | ### stopDir
|
488 |
|
489 | Type: `string`.
|
490 | Default: Absolute path to your home directory.
|
491 |
|
492 | Directory where the search will stop.
|
493 |
|
494 | ### cache
|
495 |
|
496 | Type: `boolean`.
|
497 | Default: `true`.
|
498 |
|
499 | If `false`, no caches will be used.
|
500 | Read more about ["Caching"](#caching) below.
|
501 |
|
502 | ### transform
|
503 |
|
504 | Type: `(Result) => Promise<Result> | Result`.
|
505 |
|
506 | A function that transforms the parsed configuration. Receives the [result].
|
507 |
|
508 | If 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.
|
509 | If using `cosmiconfigSync`, [`search()`] or [`load()`], the function must be synchronous and return the transformed result.
|
510 |
|
511 | The 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.
|
512 |
|
513 | ### ignoreEmptySearchPlaces
|
514 |
|
515 | Type: `boolean`.
|
516 | Default: `true`.
|
517 |
|
518 | By 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.
|
519 | If you'd like to load empty configuration files, instead, set this option to `false`.
|
520 |
|
521 | Why might you want to load empty configuration files?
|
522 | If you want to throw an error, or if an empty configuration file means something to your program.
|
523 |
|
524 | ## Loading JS modules
|
525 |
|
526 | Your end users can provide JS configuration files as ECMAScript modules (ESM) under the following conditions:
|
527 |
|
528 | - You (the cosmiconfig user) use cosmiconfig's [asynchronous API](#asynchronous-api).
|
529 | - Your end user runs a version of Node that supports ESM ([>=12.17.0](https://nodejs.org/en/blog/release/v12.17.0/), or earlier with the `--experimental-modules` flag).
|
530 | - Your end user provides an `.mjs` configuration file, or a `.js` file whose nearest parent `package.json` file contains `"type": "module"`. (See [Node's method for determining a file's module system](https://nodejs.org/api/packages.html#packages_determining_module_system).)
|
531 |
|
532 | With cosmiconfig's [asynchronous API](#asynchronous-api), the default [`searchPlaces`] include `.js`, `.ts`, `.mjs`, and `.cjs` files. Cosmiconfig loads all these file types with the [dynamic `import` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports).
|
533 |
|
534 | With the [synchronous API](#synchronous-api), JS configuration files are always treated as CommonJS, and `.mjs` files are ignored, because there is no synchronous API for the dynamic `import` function.
|
535 |
|
536 | ## Caching
|
537 |
|
538 | As 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.
|
539 |
|
540 | To avoid or work around caching, you can do the following:
|
541 |
|
542 | - Set the `cosmiconfig` option [`cache`] to `false`.
|
543 | - Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`].
|
544 | - Create separate instances of cosmiconfig (separate "explorers").
|
545 |
|
546 | ## Differences from [rc](https://github.com/dominictarr/rc)
|
547 |
|
548 | [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:
|
549 |
|
550 | - Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
|
551 | - Built-in support for JSON, YAML, and CommonJS formats.
|
552 | - Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
|
553 | - Options.
|
554 | - Asynchronous by default (though can be run synchronously).
|
555 |
|
556 | ## Usage for end users
|
557 |
|
558 | When configuring a tool, you can use multiple file formats and put these in multiple places.
|
559 |
|
560 | Usually, a tool would mention this in its own README file,
|
561 | but by default, these are the following places, where `{NAME}` represents the name of the tool:
|
562 |
|
563 | ```
|
564 | package.json
|
565 | .{NAME}rc
|
566 | .{NAME}rc.json
|
567 | .{NAME}rc.yaml
|
568 | .{NAME}rc.yml
|
569 | .{NAME}rc.js
|
570 | .{NAME}rc.ts
|
571 | .{NAME}rc.cjs
|
572 | .config/{NAME}rc
|
573 | .config/{NAME}rc.json
|
574 | .config/{NAME}rc.yaml
|
575 | .config/{NAME}rc.yml
|
576 | .config/{NAME}rc.js
|
577 | .config/{NAME}rc.ts
|
578 | .config/{NAME}rc.cjs
|
579 | {NAME}.config.js
|
580 | {NAME}.config.ts
|
581 | {NAME}.config.cjs
|
582 | ```
|
583 |
|
584 | The contents of these files are defined by the tool.
|
585 | For example, you can configure prettier to enforce semicolons at the end of the line
|
586 | using a file named `.config/prettierrc.yml`:
|
587 |
|
588 | ```yaml
|
589 | semi: true
|
590 | ```
|
591 |
|
592 | Additionally, you have the option to put a property named after the tool in your `package.json` file,
|
593 | with the contents of that property being the same as the file contents. To use the same example as above:
|
594 |
|
595 | ```json
|
596 | {
|
597 | "name": "your-project",
|
598 | "dependencies": {},
|
599 | "prettier": {
|
600 | "semi": true
|
601 | }
|
602 | }
|
603 | ```
|
604 |
|
605 | This has the advantage that you can put the configuration of all tools
|
606 | (at least the ones that use cosmiconfig) in one file.
|
607 |
|
608 | You can also add a `cosmiconfig` key within your `package.json` file or create one of the following files
|
609 | to configure `cosmiconfig` itself:
|
610 |
|
611 | ```
|
612 | .config.json
|
613 | .config.yaml
|
614 | .config.yml
|
615 | .config.js
|
616 | .config.ts
|
617 | .config.cjs
|
618 | ```
|
619 |
|
620 | The following property is currently actively supported in these places:
|
621 |
|
622 | ```yaml
|
623 | cosmiconfig:
|
624 | # overrides where configuration files are being searched to enforce a custom naming convention and format
|
625 | searchPlaces:
|
626 | - .config/{name}.yml
|
627 | ```
|
628 |
|
629 | > **Note:** technically, you can overwrite all options described in [cosmiconfigOptions](#cosmiconfigoptions) here,
|
630 | > but everything not listed above should be used at your own risk, as it has not been tested explicitly.
|
631 |
|
632 | You can also add more root properties outside the `cosmiconfig` property
|
633 | to configure your tools, entirely eliminating the need to look for additional configuration files:
|
634 |
|
635 | ```yaml
|
636 | cosmiconfig:
|
637 | searchPlaces: []
|
638 |
|
639 | prettier:
|
640 | semi: true
|
641 | ```
|
642 |
|
643 | ## Contributing & Development
|
644 |
|
645 | Please 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.
|
646 |
|
647 | And please do participate!
|
648 |
|
649 | [result]: #result
|
650 |
|
651 | [`load()`]: #explorerload
|
652 |
|
653 | [`search()`]: #explorersearch
|
654 |
|
655 | [`clearloadcache()`]: #explorerclearloadcache
|
656 |
|
657 | [`clearsearchcache()`]: #explorerclearsearchcache
|
658 |
|
659 | [`cosmiconfig()`]: #cosmiconfig
|
660 |
|
661 | [`cosmiconfigSync()`]: #cosmiconfigsync
|
662 |
|
663 | [`clearcaches()`]: #explorerclearcaches
|
664 |
|
665 | [`packageprop`]: #packageprop
|
666 |
|
667 | [`cache`]: #cache
|
668 |
|
669 | [`stopdir`]: #stopdir
|
670 |
|
671 | [`searchplaces`]: #searchplaces
|
672 |
|
673 | [`loaders`]: #loaders
|
674 |
|
675 | [`cosmiconfigoptions`]: #cosmiconfigoptions
|
676 |
|
677 | [`explorerSync.search()`]: #explorersyncsearch
|
678 |
|
679 | [`explorerSync.load()`]: #explorersyncload
|
680 |
|
681 | [`explorer.search()`]: #explorersearch
|
682 |
|
683 | [`explorer.load()`]: #explorerload
|
684 |
|
685 | ["Loading JS modules"]: #loading-js-modules
|