Skip to main content

Configuration Files

This example demonstrates how to enable loading arguments from a configuration file. The .config() method configures the CLI to load arguments from a configuration file. The method takes a single argument, a ConfigurationProvider. See the docs for ConfigurationProvider here.

For convenience, cli-forge exports some built-in configuration providers. Currently, there are two built-in configuration providers: JsonFile and PackageJson.

Usage of each of these is demonstrated below. Note that when using multiple configuration files, the order in which they are loaded is important. The last configuration file loaded will override any previously loaded configuration files.

When both environment variables and configuration files are used, the order of precedence is as follows:

  • CLI Arguments
  • Environment Variables
  • Configuration Files
  • Default Values

This is based on the idea of highest specificity. CLI Arguments are always provided directly by the user. Environment variables can change system-to-system. Configuration files are specific to the project. Default values are equal for all instances of the CLI.

Code

configured-cli.ts
import { ConfigurationProviders, cli } from 'cli-forge';

(async () =>
await cli('configured-cli', {
builder: (args) =>
args
.option('name', { type: 'string' })
.option('greeting', { type: 'string' })
.option('farewell', { type: 'string' })

// Allows loading configuration values from the 'configured-cli' entry in package.json.
.config(ConfigurationProviders.PackageJson('configured-cli'))

// Allows loading configuration values from the root of 'configured-cli.config.json'.
.config(ConfigurationProviders.JsonFile('configured-cli.config.json'))

// Allows loading configuration values from the 'configured-cli' entry in 'other.config.json'.
.config(
ConfigurationProviders.JsonFile('other.config.json', 'configured-cli')
),

handler: (args) => {
console.log(`${args.greeting}, ${args.name}!`);
console.log(`${args.farewell}, ${args.name}!`);
},
}).forge())();

configured-cli.config.json
{
"greeting": "Hello!"
}

other.config.json
{
"configured-cli": { "farewell": "Goodbye" }
}

package.json
{
"name": "some-package",
"configured-cli": {
"name": "bar"
}
}

View on TypeScript Playground

Usage

Pure Config

Note that no arguments are provided to the CLI. In this case, all arguments are being loaded from the configuration files.

node ./configuration-files.js

CLI Arguments

In this case, the CLI arguments are being used to override the configuration file.

node ./configuration-files.js --greeting "Welcome"

These examples are ran as e2e tests on pull-requests and releases to verify they are accurate and up to date. If you see any issues, please open an issue on the github repo.