yargs-parser
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
-
ReferenceError: require is not defined
cause Attempting to use `require('yargs-parser')` in an ES Module context.fixChange your import statement to `import parser from 'yargs-parser'`. -
TypeError: yargs_parser_1.default is not a function
cause This often occurs in TypeScript or transpiled JavaScript when a CommonJS `require` call (which provides a default export as `exports.default`) is consumed by an ESM `import` in a way that expects a named export, or vice-versa, specifically with `yargs-parser`'s ESM-first shift.fixEnsure your `tsconfig.json`'s `module` and `moduleResolution` settings align with your runtime environment (e.g., `"module": "NodeNext"`, `"moduleResolution": "NodeNext"` for modern Node.js ESM projects). Also, explicitly use `import parser from 'yargs-parser'` for ESM. -
Argument value is not the expected type (e.g., number parsed as string)
cause yargs-parser's default behavior or misconfiguration of `opts.number`, `opts.boolean`, or `opts.string` leads to incorrect type inference.fixExplicitly define the expected types for your arguments using the `string`, `number`, `boolean`, `array`, or `coerce` options in the `parser`'s second argument (`opts`). For example, `{ number: ['port'], string: ['host'] }`.
Warnings
- breaking yargs-parser became ESM-first in v22.0.0. This means that CommonJS `require()` statements may no longer work as expected in pure ESM Node.js projects or require explicit configuration for interoperability.
- breaking Version 21.0.0 of yargs-parser dropped official support for Node.js 10. The current minimum supported Node.js version for v22.x is ^20.19.0 || ^22.12.0 || >=23.
- gotcha Performance can degrade significantly when using the `unknown-options-as-args` configuration option, particularly with a large number of arguments or specific patterns. This was noted and addressed in patches, but users should be aware of potential impacts.
- gotcha When providing an array of arguments, `yargs-parser` expects an array of *strings*. Passing a mixed-type array (e.g., `['--foo', 123]`) directly may lead to unexpected parsing behavior or type issues.
Install
-
npm install yargs-parser -
yarn add yargs-parser -
pnpm add yargs-parser
Imports
- default
const parser = require('yargs-parser')import parser from 'yargs-parser'
- default
import parser from 'https://deno.land/x/yargs_parser/deno.ts'
- Options
import type { Options } from 'yargs-parser'
Quickstart
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);