Search code examples
javascriptyargs

How to create yargs default response when no command selected


I have created a CLI with yargs. It has a series of nested commands. All the commands work nicely, but I also want to have a welcome/info message when no command is given or if a command that does not exist is supplied.

I have been unable to get this to work, what efforts I have used either display a message all the time or not at all. Any suggestions would be welcome


Solution

  • Took quite a lot of docs reading but got there in the end, the $0 is used as a catch all command and can be added to the builder.

    yargs(hideBin(process.argv))
      .version(require('../package.json').version)
      .alias('h', 'help')
      .help()
      .command('stuff', 'makes stuff happen', () => {}, (_) => {
        ...
      })
      .command('$0', 'the default command', () => {}, (_) => {
        console.log(defaultMessage)
      })
      .parse();