How to parse commandline args with yargs in typescript

Viewed 20590

Here is what I tried (code adapted the code from the example in the yargs github readme):

// main.ts

import {Argv} from "yargs";


console.info(`CLI starter.`);

function serve(port: string) {
    console.info(`Serve on port ${port}.`);
}

require('yargs')
    .command('serve', "Start the server.", (yargs: Argv) => {
        yargs.option('port', {
            describe: "Port to bind on",
            default: "5000",
        }).option('verbose', {
            alias: 'v',
            default: false,
        })
    }, (args: any) => {
        if (args.verbose) {
            console.info("Starting the server...");
        }
        serve(args.port);
    }).argv;

Results:

npm run-script build; node build/main.js --port=432 --verbose

> typescript-cli-starter@0.0.1 build /Users/kaiyin/WebstormProjects/typescript-cli-starter
> tsc -p .

CLI starter.

Looks like yargs has no effects here.

Any idea how to get this to work?

3 Answers

a minimalistic example

import * as yargs from 'yargs'

    let args = yargs
        .option('input', {
            alias: 'i',
            demand: true
        })
        .option('year', {
            alias: 'y',
            description: "Year number",
            demand: true
        }).argv;

    console.log(JSON.stringify(args));

An example including a command and callback function:

import yargs, { Argv, ArgumentsCamelCase } from 'yargs'
import { hideBin } from 'yargs/helpers'

yargs(hideBin(process.argv))
    .command(
        'select <color>',
        'Select a color to display',
        (args: Argv) => {
            args.positional('color', {
                describe: 'The color to display. e.g.) Blue to display blue'
            })
        },
        ({ color }: ArgumentsCamelCase<{ color: string }>) => {
            console.log(`Your color is ${color}!`
        }
    )
    .demandCommand()
    .parse()

Related