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?
Yargs helps you build interactive command line tools by parsing arguments and generating an elegant user interface.
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With