yargs-parser

22.0.0 · active · verified Tue Apr 21

yargs-parser is the robust, highly configurable option parser underlying the popular yargs command-line interface library. Currently at stable version 22.0.0, it follows a release cadence tied to yargs itself, with major versions introducing breaking changes like the recent shift to ESM-first. Its key differentiators include comprehensive argument parsing capabilities, extensive configuration options for aliases, types (boolean, number, string, array), defaults, environment variable handling, and support for configuration files. It operates efficiently across various JavaScript environments, including Node.js (requiring Node.js ^20.19.0 || ^22.12.0 || >=23 as of v22), web browsers via specific builds, and Deno, making it a versatile choice for parsing CLI arguments or arbitrary strings.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing command-line arguments using various configuration options like types, aliases, defaults, and custom coercions.

import parser from 'yargs-parser';
import process from 'node:process';

// Example 1: Parsing process arguments with various options
const args = process.argv.slice(2);
const argvParsed = parser(args, {
  string: ['name', 'city'], // Treat these keys as strings
  boolean: ['verbose', 'help'], // Treat these keys as booleans
  alias: {
    name: ['n'], // -n is an alias for --name
    verbose: ['v'], // -v is an alias for --verbose
    help: ['h'] // -h is an alias for --help
  },
  default: {
    verbose: false,
    city: 'Unknown'
  },
  // unknown-options-as-args: true // Uncomment to treat unknown options as positional arguments
});

console.log('Parsed process arguments:', argvParsed);
// To run: node your-script.js --name "Alice Smith" -v --city London --project Foo --bar

// Example 2: Parsing a string directly with coercion and array handling
const stringArgs = '--count=5 --active --tags one two three --price 10.50';
const stringParsed = parser(stringArgs, {
  count: ['count'], // Interpret multiple occurrences of --count as a counter (e.g., -vvv = {v:3})
  boolean: ['active'],
  array: ['tags'], // Collect multiple --tags values into an array
  number: ['price'],
  coerce: {
    // Custom coercion for tags to uppercase
    tags: (arr) => Array.isArray(arr) ? arr.map(tag => String(tag).toUpperCase()) : [String(arr).toUpperCase()],
  }
});
console.log('Parsed string arguments with coercion:', stringParsed);

view raw JSON →