You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

581 lines
19 KiB

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