Lesson 54 of 56 · Typescript
CLI Tool Project – `commander` in TypeScript
Duration: 25 minutes
Install commander
npm i commander
npm i -D @types/commander
Basic CLI
#!/usr/bin/env node
import { Command } from 'commander';
const program = new Command();
program
.name('calc')
.description('Simple arithmetic calculator')
.option('-v, --verbose', 'Enable verbose output')
.argument('<a>', 'first operand', parseFloat)
.argument('<b>', 'second operand', parseFloat)
.argument('<op>', 'operation: add|sub|mul|div')
.action((a: number, b: number, op: string, opts) => {
let result: number;
switch (op) {
case 'add': result = a + b; break;
case 'sub': result = a - b; break;
case 'mul': result = a * b; break;
case 'div':
if (b === 0) { console.error('Division by zero'); process.exit(1); }
result = a / b; break;
default:
console.error('Unknown operation'); process.exit(1);
}
if (opts.verbose) console.info(`Calculating ${a} ${op} ${b}`);
console.log(result);
});
program.parse();
Make the file executable (chmod +x cli.ts) and add a bin entry in package.json:
"bin": { "calc": "dist/cli.js" }
Build with tsc and publish.