Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse commandline args with yargs in typescript

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

> [email protected] 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?

like image 406
qed Avatar asked Jul 13 '17 10:07

qed


People also ask

What is Yargs parser?

Yargs helps you build interactive command line tools by parsing arguments and generating an elegant user interface.


2 Answers

I adapted the code from the example in the yargs github readme, turns out it's not meant to be a complete example. ¯_(ツ)_/¯

Anyways, I figured out how to do it:

#!/usr/bin/env node

import yargs, {Argv} from "yargs";

let argv = yargs
    .command('serve', "Start the server.", (yargs: Argv) => {
        return yargs.option('port', {
            describe: "Port to bind on",
            default: "5000",
        }).option('verbose', {
            alias: 'v',
            default: false,
        })
    }).argv;

if (argv.verbose) {
    console.info("Verbose mode on.");
}

serve(argv.port);

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

You can find the complete typescript-cli-starter repo here: https://github.com/kindlychung/typescript-cli-starter

like image 72
qed Avatar answered Oct 27 '22 10:10

qed


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));
like image 44
Andrey Avatar answered Oct 27 '22 10:10

Andrey