Node.js CLI Tool with Commander

Build a type-safe CLI tool in Node.js using Commander.js with subcommands, option parsing, help generation, and TypeScript. Includes chalk-colored output.

TypescriptNodeCli Tooling

Code

snippet
import { Command } from 'commander';
import chalk from 'chalk';

const program = new Command();

program
  .name('mycli')
  .description('A type-safe CLI tool')
  .version('1.0.0');

program
  .command('build <input>')
  .option('-o, --output <path>', 'output directory', 'dist')
  .option('--minify', 'minify output', false)
  .action((input: string, opts: { output: string; minify: boolean }) => {
    console.log(chalk.green(`Building ${input} → ${opts.output}`));
    if (opts.minify) console.log(chalk.gray('Minification enabled'));
  });

program.parse();

Inside the snippet

Command are the only symbols borrowed from commander — the coupling is explicit and narrow.

Top-level bindings program hold the demo state — nothing sits inside a function scope.

Watch out for

  • Plan for an install step: commander and chalk are a real dependency, resolved by the package manager.

Core lines

.action((input: string, opts: { output: string; minify: boolean }) => {
  console.log(chalk.green(`Building ${input} → ${opts.output}`));
  if (opts.minify) console.log(chalk.gray('Minification enabled'));
});

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`commander` and `chalk` — install them with the package manager before running.