Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

yargs

yargs431.8mMIT17.7.2TypeScript support: included

yargs the modern, pirate-themed, successor to optimist.

argument, args, option, parser, parsing, cli, command

readme

Yargs

Yargs be a node.js library fer hearties tryin' ter parse optstrings


ci NPM version js-standard-style Coverage Conventional Commits Slack

Description

Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.

It gives you:

  • commands and (grouped) options (my-program.js serve --port=5000).
  • a dynamically generated help menu based on your arguments:
mocha [spec..]

Run tests with Mocha

Commands
  mocha inspect [spec..]  Run tests with Mocha                         [default]
  mocha init <path>       create a client-side Mocha setup at <path>

Rules & Behavior
  --allow-uncaught           Allow uncaught errors to propagate        [boolean]
  --async-only, -A           Require all tests to use a callback (async) or
                             return a Promise                          [boolean]
  • bash-completion shortcuts for commands and options.
  • and tons more.

Installation

Stable version:

npm i yargs

Bleeding edge version with the most recent features:

npm i yargs@next

Usage

Simple Example

#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv

if (argv.ships > 3 && argv.distance < 53.5) {
  console.log('Plunder more riffiwobbles!')
} else {
  console.log('Retreat from the xupptumblers!')
}
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!

$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!

Note: hideBin is a shorthand for process.argv.slice(2). It has the benefit that it takes into account variations in some environments, e.g., Electron.

Complex Example

#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')

yargs(hideBin(process.argv))
  .command('serve [port]', 'start the server', (yargs) => {
    return yargs
      .positional('port', {
        describe: 'port to bind on',
        default: 5000
      })
  }, (argv) => {
    if (argv.verbose) console.info(`start server on :${argv.port}`)
    serve(argv.port)
  })
  .option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging'
  })
  .parse()

Run the example above with --help to see the help for the application.

Supported Platforms

TypeScript

yargs has type definitions at @types/yargs.

npm i @types/yargs --save-dev

See usage examples in docs.

Deno

As of v16, yargs supports Deno:

import yargs from 'https://deno.land/x/yargs/deno.ts'
import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts'

yargs(Deno.args)
  .command('download <files...>', 'download a list of files', (yargs: any) => {
    return yargs.positional('files', {
      describe: 'a list of files to do something with'
    })
  }, (argv: Arguments) => {
    console.info(argv)
  })
  .strictCommands()
  .demandCommand(1)
  .parse()

ESM

As of v16,yargs supports ESM imports:

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

yargs(hideBin(process.argv))
  .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => {
    console.info(argv)
  })
  .demandCommand(1)
  .parse()

Usage in Browser

See examples of using yargs in the browser in docs.

Community

Having problems? want to contribute? join our community slack.

Documentation

Table of Contents

Supported Node.js Versions

Libraries in this ecosystem make a best effort to track Node.js' release schedule. Here's a post on why we think this is important.

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

17.7.2 (2023-04-27)

Bug Fixes

  • do not crash completion when having negated options (#2322) (7f42848)

17.7.1 (2023-02-21)

Bug Fixes

  • address display bug with default sub-commands (#2303) (9aa2490)

17.7.0 (2023-02-13)

Features

  • add method to hide option extras (#2156) (2c144c4)
  • convert line break to whitespace for the description of the option (#2271) (4cb41dc)

Bug Fixes

  • copy the description of the option to its alias in completion (#2269) (f37ee6f)

17.6.2 (2022-11-03)

Bug Fixes

  • deps: update dependency yargs-parser to v21.1.1 (#2231) (75b4d52)
  • lang: typo in Finnish unknown argument singular form (#2222) (a6dfd0a)

17.6.1 (2022-11-02)

Bug Fixes

  • lang: fix "Not enough non-option arguments" message for the Czech language (#2242) (3987b13)

17.6.0 (2022-10-01)

Features

Bug Fixes

  • deno: use 'globalThis' instead of 'window' (#2186) (#2215) (561fc7a)
  • deps: cliui with forced strip-ansi update (#2241) (38e8df1)
  • dont clobber description for multiple option calls (#2171) (f91d9b3)
  • typescript: address warning with objectKeys (394f5f8)

17.5.1 (2022-05-16)

Bug Fixes

  • add missing entries to published files (#2185) (5685382)
  • address bug when strict and async middleware used together (#2164) (cbc2eb7)
  • completion: correct zsh installation instructions (22e9af2)
  • handle multiple node_modules folders determining mainFilename for ESM (#2123) (e0823dd)
  • lang: add missing terms to Russian translation (#2181) (1c331f2)
  • prevent infinite loop with empty locale (#2179) (b672e70)
  • veriadic arguments override array provided in config (the same as multiple dash arguments). (4dac5b8)

17.5.0 (2022-05-11)

Features

  • add browser.d.ts and check for existence of Error.captureStackTrace() (#2144) (6192990)

Bug Fixes

  • completion: support for default flags (db35423)
  • import yargs/yargs in esm projects (#2151) (95aed1c)

17.4.1 (2022-04-09)

Bug Fixes

17.4.0 (2022-03-19)

Features

  • completion: choices will now work for all possible aliases of an option and not just the default long option (30edd50)
  • completion: positional arguments completion (#2090) (00e4ebb)

Bug Fixes

  • completion: changed the check for option arguments to match options that begin with '-', instead of '--', to include short options (30edd50)
  • completion: fix for completions that contain non-leading hyphens (30edd50)
  • failed command usage string is missing arg descriptions and optional args (#2105) (d6e342d)
  • wrap unknown args in quotes (#2092) (6a29778)

17.3.1 (2021-12-23)

Bug Fixes

  • translations: correct Korean translation (#2095) (c7c2b9e)

17.3.0 (2021-11-30)

Features

  • fallback to default bash completion (74c0ba5)

Bug Fixes

  • avoid legacy accessors (#2013) (adb0d11)
  • deps: update dependency yargs-parser to v21 (#2063) (76c1951)
  • don't fail if "fileURLToPath(import.meta.url)" throws (3a44796)
  • re-add options to check callback (#2079) (e75319d)

17.2.1 (2021-09-25)

Bug Fixes

17.2.0 (2021-09-23)

Features

Bug Fixes

  • boolean option should work with strict (#1996) (e9379e2)
  • cast error types as TypeScript 4.4 infers them as unknown instead of any (#2016) (01b2c6a)
  • conflicts and strip-dashed (#1998) (59a86fb)
  • emit warning on version name collision (#1986) (d0e8292)
  • help command spacing when scriptName is empty (#1994) (d33e997)

17.1.1 (2021-08-13)

Bug Fixes

  • positional array defaults should not be combined with provided values (#2006) (832222d)

17.1.0 (2021-08-04)

Features

  • update Levenshtein to Damerau-Levenshtein (#1973) (d2c121b)

Bug Fixes

  • coerce middleware should be applied once (#1978) (14bd6be)
  • implies should not fail when implied key's value is 0, false or empty string (#1985) (8010472)
  • positionals should not overwrite options (#1992) (9d84309)
  • strict should fail unknown arguments (#1977) (c804f0d)
  • wrap(null) no longer causes strange indentation behavior (#1988) (e1871aa)

17.0.1 (2021-05-03)

Bug Fixes

17.0.0 (2021-05-02)

⚠ BREAKING CHANGES

  • node: drop Node 10 (#1919)
  • implicitly private methods are now actually private
  • deprecated reset() method is now private (call yargs() instead).
  • yargs-factory: refactor yargs-factory to use class (#1895)
  • .positional() now allowed at root level of yargs.
  • coerce: coerce is now applied before validation.
  • async: yargs now returns a promise if async or check are asynchronous.
  • middleware: global middleware now applied when no command is configured.
  • 1823 contains the following breaking API changes:

    • now returns a promise if handler is async.
    • onFinishCommand removed, in favor of being able to await promise.
    • getCompletion now invokes callback with err and `completions, returns promise of completions.

Features

  • add commands alias (similar to options function) (#1850) (00b74ad)
  • add parseSync/parseAsync method (#1898) (6130ad8)
  • add support for showVersion, similar to showHelp (#1831) (1a1e2d5)
  • adds support for async builder (#1888) (ade29b8), closes #1042
  • allow calling standard completion function from custom one (#1855) (31765cb)
  • allow default completion to be referenced and modified, in custom completion (#1878) (01619f6)
  • async: add support for async check and coerce (#1872) (8b95f57)
  • improve support for async/await (#1823) (169b815)
  • locale: add Ukrainian locale (#1893) (c872dfc)
  • middleware: async middleware can now be used before validation. (e0f9363)
  • middleware: global middleware now applied when no command is configured. (e0f9363)
  • node: drop Node 10 (#1919) (5edeb9e)

Bug Fixes

Code Refactoring

  • coerce: coerce is now applied before validation. (8b95f57)
  • deprecated reset() method is now private (call yargs() instead). (376f892)
  • implicitly private methods are now actually private (376f892)
  • yargs-factory: refactor yargs-factory to use class (#1895) (376f892)

16.2.0 (2020-12-05)

Features

  • command() now accepts an array of modules (f415388)

Bug Fixes

16.1.1 (2020-11-15)

Bug Fixes

16.1.0 (2020-10-15)

Features

Bug Fixes

  • deno: update types for deno ^1.4.0 (#1772) (0801752)
  • exports: node 13.0-13.6 require a string fallback (#1776) (b45c43a)
  • modules: module path was incorrect (#1759) (95a4a0a)
  • positional: positional strings no longer drop decimals (#1761) (e1a300f)
  • make positionals in -- count towards validation (#1752) (eb2b29d)

16.0.3 (2020-09-10)

Bug Fixes

  • move yargs.cjs to yargs to fix Node 10 imports (#1747) (5bfb85b)

16.0.2 (2020-09-09)

Bug Fixes

  • typescript: yargs-parser was breaking @types/yargs (#1745) (2253284)

16.0.1 (2020-09-09)

Bug Fixes

16.0.0 (2020-09-09)

⚠ BREAKING CHANGES

  • tweaks to ESM/Deno API surface: now exports yargs function by default; getProcessArgvWithoutBin becomes hideBin; types now exported for Deno.
  • find-up replaced with escalade; export map added (limits importable files in Node >= 12); yarser-parser@19.x.x (new decamelize/camelcase implementation).
  • usage: single character aliases are now shown first in help output
  • rebase helper is no longer provided on yargs instance.
  • drop support for EOL Node 8 (#1686)

Features

Bug Fixes

Older CHANGELOG Entries