Inquirer with yargs


This post goes over how to use Inquirer with yargs.

Inquirier

Prompt for name:

const inquirer = require('inquirer');

(async () => {
  const answers = await inquirer.prompt([
    {
      message: 'What is your name?',
      name: 'name',
      type: 'string',
    },
  ]);

  console.log(`Hello, ${answers.name}!`);
})();

Yargs

Parse command-line arguments with name option:

const { hideBin } = require('yargs/helpers');
const yargs = require('yargs/yargs');

(async () => {
  const argv = yargs(hideBin(process.argv))
    .options({
      name: {
        demandOption: true,
        describe: 'Your name',
        type: 'string',
      },
    })
    .parseSync();

  console.log(`Hello, ${argv.name}!`);
})();

Inquirer with yargs

Prompt with Inquirer before parsing arguments with yargs:

const inquirer = require('inquirer');
const { hideBin } = require('yargs/helpers');
const yargs = require('yargs/yargs');

const options = {
  name: {
    // inquirer
    message: 'What is your name?',
    name: 'name',
    // yargs
    demandOption: true,
    describe: 'Your name',
    // shared
    type: 'string',
  },
};

(async () => {
  const answers = await inquirer.prompt(Object.values(options));

  Object.entries(answers).forEach(([key, value]) => {
    value && process.argv.push(`--${key}`, value);
  });

  const argv = yargs(hideBin(process.argv)).options(options).parseSync();

  console.log(`Hello, ${argv.name}!`);
})();

Demo

Replit example:



Please support this site and join our Discord!