Basic CLI
This is a simple example that demonstrates how to create a basic CLI using cli-forge
1 FILESTry in Playground
All Example Files
FILE EXPLORER
basic-cli.ts
1import cliForge from 'cli-forge';
2
3const cli = cliForge('basic-cli')
4 // Requires a command to be provided
5 .demandCommand()
6
7 // Registers "hello" command
8 .command('hello', {
9 // Builder is used to define the command's options
10 builder: (args) =>
11 args.option('name', {
12 type: 'string',
13 description: 'The name to say hello to',
14 default: 'World',
15 }),
16 // Handler is used to define the command's behavior
17 handler: (args) => {
18 // Note: name is always defined because it has a default value.
19 console.log(`Hello, ${args.name}!`);
20 },
21 })
22 .command('goodbye', {
23 builder: (args) =>
24 args
25 .option('name', {
26 type: 'string',
27 description: 'The name to say goodbye to',
28 default: 'World',
29 })
30 .option('excited', {
31 type: 'boolean',
32 description: 'Whether to say goodbye excitedly',
33 }),
34 handler: (args) => {
35 // Note the typing of `args` here. It's inferred from the builder.
36 // The `name` option is always defined because it has a default value.
37 // The `excited` option is optional because it doesn't have a default value.
38 console.log(`Goodbye, ${args.name}${args.excited ? '!' : '.'}`);
39 },
40 });
41
42// We export the CLI for a few reasons:
43// - Testing
44// - Composition (a CLI can be a subcommand of another CLI)
45// - Docs generation
46export default cli;
47
48// Calling `.forge()` executes the CLI. It's single parameter is the CLI args
49// and they default to `process.argv.slice(2)`.
50if (require.main === module) {
51 (async () => {
52 await cli.forge();
53 })();
54}
55