Default Values

This is a simple example that demonstrates the various ways you can set default values for options.

The default value can be set via the default property in an option definition. This can be done in three ways:

  • Setting the default property to a value directly
  • Setting the default property to an object containing function that returns a value and a description
  • Setting the default property to an object containing a value and a description

Setting the default property to a value directly is the simplest way to set a default value, but can lead to some odd behavior if the value isn't consistent. For example, if the default value is the value of an environment variable that may differ among users then the actual default value will be different for each user. In this case in documentation, it would be better to tell users a description of the default value rather than the actual value.

All Example Files

FILE EXPLORER
default-values.ts
1import cliForge from 'cli-forge';
2
3const cli = cliForge('default-values').command('$0', {
4  builder: (args) =>
5    args
6      .option('name', {
7        type: 'string',
8        description: 'The name to say hello to',
9        // Setting the default value directly
10        default: 'World',
11      })
12      .option('greeting', {
13        type: 'string',
14        description: 'The greeting to use',
15        // Setting the default value to an object containing a value and a description
16        default: {
17          // The value here may be different across command runs. In docs,
18          // we want a consistent description of the default value.
19          value: process.env['DEFAULT_VALUES_HELLO'] ?? 'Hello',
20          description: 'The default greeting',
21        },
22      })
23      .option('farewell', {
24        type: 'string',
25        description: 'The farewell to use',
26        // Setting the default value to an object containing a function that returns a value and a description
27        default: {
28          // The value here may be different across command runs. In docs,
29          // we want a consistent description of the default. Using a factory function
30          // gives more flexibility compared to the value + description method above.
31          factory: () => {
32            if (process.arch === 'x64') {
33              return 'Goodbye';
34            } else {
35              return 'Goodnight';
36            }
37          },
38          description: 'The default farewell',
39        },
40      }),
41  handler: (args) => {
42    console.log(`${args.greeting}, ${args.name}!`);
43    console.log(`${args.farewell}, ${args.name}!`);
44  },
45});
46
47export default cli;
48
49if (require.main === module) {
50  (async () => {
51    await cli.forge();
52  })();
53}
54