philip yoo
philip yoo

Reputation: 2512

Can you reuse options defined in other commands using commander.js?

So I have several commands and they all use the same options.

For example..

program.command('hello')
    .option('--foo <name>', 'this is the foo option and requires a name')
    .option('--bar', 'this is the bar option and takes no arguments')
    .action(options => {
        // do stuff here...
    });

program.command('world')
    .option('--foo <name>', 'this is the foo option and requires a name')
    .option('--bar', 'this is the bar option and takes no arguments')
    .action(options => {
        // do stuff here...
    });

I'd like to refactor this and define the options once. However, action taken for each command may differ.

Is there a way to declare options once and use them for any/all commands defined?

Upvotes: 2

Views: 497

Answers (2)

baruchiro
baruchiro

Reputation: 5801

You can build your shared command, then you can add to it the specific configuration.

Initialize your shared item:

const createCommandWithSharedOptions = () => new program.Command()
    .option('--foo <name>', 'this is the foo option and requires a name')
    .option('--bar', 'this is the bar option and takes no arguments')

Define your custom command based on the shared init:

const hello = createCommandWithSharedOptions().name('hello').arguments('<req> [opt]')
const world = createCommandWithSharedOptions().name('world')

Add them to the program:

program.addCommand(hello).addCommand(world)

Upvotes: 3

philip yoo
philip yoo

Reputation: 2512

The solution I came up with only works for commands that have the same exact options. To work with unique options, you would have to probably extend the solution I found, or maybe there is another way as well.

What I came up with:

[
    {
        name: 'hello',
        method: 'hiMethod'
    },
    {
        name: 'world',
        method: 'woMethod',
    },
].forEach(cmd => {
    program.command(cmd.name)
        .option('--foo <name>', 'this is the foo option and requires a name')
        .option('--bar', 'this is the bar option and takes no arguments')
        .action(options => {
            // do stuff here...
            // I can use `cmd.method` for unique actions for each command
        });
});

This solution worked for me :)

Upvotes: 0

Related Questions