or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

command-system.mdcore-parser.mdhelp-output.mdindex.mdoption-definition.mdparsing.mdvalidation.md
tile.json

tessl/npm-yargs

Command-line argument parsing library for Node.js with commands, options, and validation.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/yargs@18.0.x

To install, run

npx @tessl/cli install tessl/npm-yargs@18.0.0

index.mddocs/

Yargs

Yargs is a comprehensive command-line argument parsing library for Node.js that helps developers build interactive CLI tools with minimal effort. It provides powerful features including command definition with subcommands and grouped options, automatic help menu generation, support for positional and named parameters with type validation, built-in completion script generation, and extensive customization options for parsing behavior.

Package Information

  • Package Name: yargs
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install yargs

Core Imports

ESM (recommended):

import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';

CommonJS:

const yargs = require('yargs');
const { hideBin } = require('yargs/helpers');

Browser:

import yargs from 'yargs/browser';

Basic Usage

import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';

// Simple argument parsing
const argv = yargs(hideBin(process.argv))
  .option('port', {
    alias: 'p',
    type: 'number',
    default: 3000,
    description: 'Port to bind on'
  })
  .option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging'
  })
  .parse();

console.log(`Server running on port ${argv.port}`);
if (argv.verbose) console.log('Verbose mode enabled');

Architecture

Yargs is built around several key components:

  • Yargs Factory: Main entry point that creates parser instances with platform-specific shims
  • Fluent Interface: Chainable API allowing method calls to configure parsing behavior
  • Command System: Hierarchical command structure with subcommands and command-specific options
  • Option Definition: Comprehensive option configuration with types, validation, and relationships
  • Middleware System: Pipeline for transforming arguments during parsing
  • Validation Engine: Built-in validation with custom validation support
  • Help Generation: Automatic help text generation based on configuration
  • Completion System: Shell completion script generation for Bash and Zsh

Capabilities

Core Parser Configuration

Primary yargs factory function and fundamental configuration methods for setting up argument parsing behavior.

/**
 * Creates a new yargs parser instance
 * @param processArgs - Arguments to parse (default: [])
 * @param cwd - Current working directory
 * @param parentRequire - Parent require function
 * @returns YargsInstance for method chaining
 */
function yargs(processArgs?: string | string[], cwd?: string, parentRequire?: Function): YargsInstance;

Core Parser Configuration

Option Definition

Define and configure command-line options with types, validation, defaults, and relationships between options.

/**
 * Define a command-line option
 * @param key - Option name or configuration object
 * @param opt - Option configuration
 * @returns YargsInstance for chaining
 */
option(key: string | Dictionary<OptionDefinition>, opt?: OptionDefinition): YargsInstance;

/**
 * Define option aliases
 * @param key - Option name, array of names, or alias map
 * @param value - Alias name(s) for the option
 * @returns YargsInstance for chaining
 */
alias(key: string | string[] | Dictionary<string | string[]>, value?: string | string[]): YargsInstance;

/**
 * Set default values for options
 * @param key - Option name, array, or defaults object
 * @param value - Default value
 * @param defaultDescription - Description of default value
 * @returns YargsInstance for chaining
 */
default(key: string | string[] | Dictionary<any>, value?: any, defaultDescription?: string): YargsInstance;

Option Definition

Command System

Define commands, subcommands, and positional arguments with custom handlers and builders.

/**
 * Define a command with optional subcommands and handlers
 * @param cmd - Command string, definition object, or array
 * @param description - Command description
 * @param builder - Function or object to configure command options
 * @param handler - Function to execute when command is called
 * @param middlewares - Array of middleware functions
 * @param deprecated - Mark command as deprecated
 * @returns YargsInstance for chaining
 */
command(
  cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
  description?: string | boolean,
  builder?: CommandBuilderDefinition | CommandBuilder,
  handler?: CommandHandlerCallback,
  middlewares?: Middleware[],
  deprecated?: boolean
): YargsInstance;

/**
 * Define positional argument within a command
 * @param key - Positional argument name
 * @param opts - Positional argument configuration
 * @returns YargsInstance for chaining
 */
positional(key: string, opts: PositionalDefinition): YargsInstance;

Command System

Validation and Requirements

Validate arguments, define required options and commands, and set up option relationships.

/**
 * Require minimum/maximum number of commands
 * @param min - Minimum number of commands (default: 1)
 * @param max - Maximum number of commands
 * @param minMsg - Message for too few commands
 * @param maxMsg - Message for too many commands
 * @returns YargsInstance for chaining
 */
demandCommand(min?: number, max?: number | string, minMsg?: string | null, maxMsg?: string | null): YargsInstance;

/**
 * Make options required
 * @param keys - Option name(s) or requirements object
 * @param msg - Error message for missing option
 * @returns YargsInstance for chaining
 */
demandOption(keys: string | string[] | Dictionary<string | undefined>, msg?: string): YargsInstance;

/**
 * Define conflicting options
 * @param key1 - First option or conflicts map
 * @param key2 - Second option name(s)
 * @returns YargsInstance for chaining
 */
conflicts(key1: string | Dictionary<string | string[]>, key2?: string | string[]): YargsInstance;

Validation and Requirements

Help and Output

Configure help system, version information, usage messages, and output formatting.

/**
 * Configure help option
 * @param opt - Help option name or false to disable
 * @param msg - Help option description
 * @returns YargsInstance for chaining
 */
help(opt?: string | false, msg?: string): YargsInstance;

/**
 * Configure version option
 * @param opt - Version option name or false to disable
 * @param msg - Version option description
 * @param ver - Version string
 * @returns YargsInstance for chaining
 */
version(opt?: string | false, msg?: string, ver?: string): YargsInstance;

/**
 * Set usage message or define default command
 * @param msg - Usage message template
 * @param description - Command description (if defining command)
 * @param builder - Command builder
 * @param handler - Command handler
 * @returns YargsInstance for chaining
 */
usage(msg: string | null, description?: string | boolean, builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback): YargsInstance;

Help and Output

Middleware and Processing

Add custom middleware functions to process arguments during parsing.

/**
 * Add middleware function to processing pipeline
 * @param callback - Middleware function to add
 * @param applyBeforeValidation - Whether to run before validation
 * @param global - Whether middleware applies globally
 * @returns YargsInstance for chaining
 */
middleware(callback: MiddlewareCallback, applyBeforeValidation?: boolean, global?: boolean): YargsInstance;

/**
 * Add validation check function
 * @param f - Validation function
 * @param global - Whether check applies globally
 * @returns YargsInstance for chaining
 */
check(f: CheckCallback, global?: boolean): YargsInstance;

Parsing and Execution

Parse arguments and execute commands with support for both synchronous and asynchronous operations.

/**
 * Parse arguments (sync or async based on middleware/handlers)
 * @param args - Arguments to parse
 * @param shortCircuit - Context object or callback
 * @param _parseFn - Parse callback function
 * @returns Parsed arguments or Promise
 */
parse(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments | Promise<Arguments>;

/**
 * Parse arguments asynchronously
 * @param args - Arguments to parse
 * @param shortCircuit - Context object or callback
 * @param _parseFn - Parse callback function
 * @returns Promise resolving to parsed arguments
 */
parseAsync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Promise<Arguments>;

/**
 * Parse arguments synchronously (throws if async middleware/handlers used)
 * @param args - Arguments to parse
 * @param shortCircuit - Context object or callback
 * @param _parseFn - Parse callback function
 * @returns Parsed arguments
 */
parseSync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments;

Parsing and Execution

Helper Functions

Utility functions for common yargs operations, available from the separate helpers module.

/**
 * Remove binary name and script name from process.argv
 * @param argv - Process arguments array (typically process.argv)
 * @returns Arguments array with binary and script names removed
 */
function hideBin(argv: string[]): string[];

/**
 * Apply configuration extensions and inheritance
 * @param config - Configuration object to extend
 * @param cwd - Current working directory
 * @param mergeExtends - Whether to merge extends deeply
 * @returns Extended configuration object
 */
function applyExtends(config: object, cwd: string, mergeExtends?: boolean): object;

/**
 * Low-level argument parser (re-exported from yargs-parser)
 */
const Parser: typeof YargsParser;

Usage Examples:

import yargs from 'yargs';
import { hideBin, applyExtends, Parser } from 'yargs/helpers';

// Most common usage - remove node and script from process.argv
const argv = yargs(hideBin(process.argv)).parse();

// Direct parser usage (advanced)
const parsed = Parser(['--port', '3000', '--verbose']);
console.log(parsed); // { port: 3000, verbose: true, _: [] }

// Config extension (typically internal use)
const baseConfig = { port: 3000 };
const extended = applyExtends(baseConfig, process.cwd());

Global Types

/**
 * Parsed command-line arguments
 */
interface Arguments {
  /** Script name or node command */
  $0: string;
  /** Non-option arguments */
  _: (string | number)[];
  /** Arguments after the end-of-options flag -- */
  '--'?: (string | number)[];
  /** All remaining options */
  [argName: string]: any;
}

/**
 * Option definition configuration
 */
interface OptionDefinition {
  alias?: string | string[];
  array?: boolean;
  boolean?: boolean;
  choices?: string | string[];
  coerce?: (arg: any) => any;
  config?: boolean;
  configParser?: (configPath: string) => object;
  conflicts?: string | string[];
  count?: boolean;
  default?: any;
  defaultDescription?: string;
  deprecate?: string | boolean;
  deprecated?: string | boolean;
  desc?: string;
  describe?: string;
  description?: string;
  demand?: string | true;
  demandOption?: string | true;
  global?: boolean;
  group?: string;
  hidden?: boolean;
  implies?: string | number | (string | number)[];
  nargs?: number;
  normalize?: boolean;
  number?: boolean;
  require?: string | true;
  required?: string | true;
  requiresArg?: boolean;
  skipValidation?: boolean;
  string?: boolean;
  type?: 'array' | 'boolean' | 'count' | 'number' | 'string';
}

/**
 * Command handler callback function
 */
type CommandHandlerCallback = (argv: Arguments) => void | Promise<void>;

/**
 * Command builder function
 */
type CommandBuilder = (yargs: YargsInstance) => YargsInstance | Promise<YargsInstance>;

/**
 * Parse callback for handling results
 */
interface ParseCallback {
  (err: Error | string | null, argv: Arguments, output: string): void;
}

/**
 * Middleware callback function
 */
type MiddlewareCallback = (argv: Arguments, yargs: YargsInstance) => void | Arguments | Promise<void | Arguments>;

/**
 * Check callback function
 */
type CheckCallback = (argv: Arguments, options: Options) => boolean | string | Error | void | Promise<boolean | string | Error | void>;