Introduction
Yargs is a Node.js library for parsing command-line arguments with support for commands, options, positional arguments, and automatic help generation. It provides a fluent API that makes building complex CLI applications straightforward while handling edge cases like aliases, defaults, and type coercion.
What Yargs Does
- Parses command-line arguments into a structured object with type coercion
- Supports nested commands with dedicated handlers and options
- Generates
--helpand--versionoutput automatically - Validates required arguments, choices, and custom constraints
- Reads configuration from environment variables, config files, and
.rcfiles
Architecture Overview
Yargs processes arguments in stages: first it tokenizes process.argv using yargs-parser, splitting flags, values, and positional arguments. Then it matches the tokens against registered commands and options, applies defaults and type coercion, runs validation checks, and invokes the matched command handler with the parsed argv object. The middleware system allows pre-processing steps between parsing and handler execution.
Self-Hosting & Configuration
- Install via npm:
npm install yargs - Use
yargs(process.argv.slice(2))or thehideBinhelper to strip node and script paths - Define commands with
.command(name, description, builder, handler) - Set global options with
.option(key, { alias, type, default, describe }) - Enable strict mode with
.strict()to reject unrecognized arguments
Key Features
- Fluent API chains commands, options, and middleware in a readable builder pattern
- Async command handlers with built-in promise support
- Middleware functions run before command handlers for logging, auth, or data loading
- Completion script generation for bash and zsh
- Localization support for help text in multiple languages
Comparison with Similar Tools
- Commander.js — similar scope but uses a different API style; Yargs has richer validation and middleware
- Meow — lighter weight for simple CLIs; Yargs handles complex command hierarchies
- Oclif — full CLI framework with plugins and testing; Yargs is a library, not a framework
- cac — smaller and faster for basic parsing; Yargs provides more built-in features
FAQ
Q: How do I handle subcommands?
A: Use .command() for each subcommand. Nest them by calling .command() inside the builder function of a parent command.
Q: Can Yargs read from config files?
A: Yes. Use .config() to load a JSON config file, or .env(prefix) to read from environment variables.
Q: Does Yargs support TypeScript? A: Yes. Yargs ships with TypeScript type definitions and supports generic typing for parsed arguments.
Q: How do I generate shell completions?
A: Call .completion() to add a hidden completion command, then run your-cli completion >> ~/.bashrc.