Command-line argument parsing library for Node.js with commands, options, and validation.
npx @tessl/cli install tessl/npm-yargs@18.0.00
# Yargs
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: yargs
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install yargs`
10
11
## Core Imports
12
13
ESM (recommended):
14
```javascript
15
import yargs from 'yargs';
16
import { hideBin } from 'yargs/helpers';
17
```
18
19
CommonJS:
20
```javascript
21
const yargs = require('yargs');
22
const { hideBin } = require('yargs/helpers');
23
```
24
25
Browser:
26
```javascript
27
import yargs from 'yargs/browser';
28
```
29
30
## Basic Usage
31
32
```javascript
33
import yargs from 'yargs';
34
import { hideBin } from 'yargs/helpers';
35
36
// Simple argument parsing
37
const argv = yargs(hideBin(process.argv))
38
.option('port', {
39
alias: 'p',
40
type: 'number',
41
default: 3000,
42
description: 'Port to bind on'
43
})
44
.option('verbose', {
45
alias: 'v',
46
type: 'boolean',
47
description: 'Run with verbose logging'
48
})
49
.parse();
50
51
console.log(`Server running on port ${argv.port}`);
52
if (argv.verbose) console.log('Verbose mode enabled');
53
```
54
55
## Architecture
56
57
Yargs is built around several key components:
58
59
- **Yargs Factory**: Main entry point that creates parser instances with platform-specific shims
60
- **Fluent Interface**: Chainable API allowing method calls to configure parsing behavior
61
- **Command System**: Hierarchical command structure with subcommands and command-specific options
62
- **Option Definition**: Comprehensive option configuration with types, validation, and relationships
63
- **Middleware System**: Pipeline for transforming arguments during parsing
64
- **Validation Engine**: Built-in validation with custom validation support
65
- **Help Generation**: Automatic help text generation based on configuration
66
- **Completion System**: Shell completion script generation for Bash and Zsh
67
68
## Capabilities
69
70
### Core Parser Configuration
71
72
Primary yargs factory function and fundamental configuration methods for setting up argument parsing behavior.
73
74
```javascript { .api }
75
/**
76
* Creates a new yargs parser instance
77
* @param processArgs - Arguments to parse (default: [])
78
* @param cwd - Current working directory
79
* @param parentRequire - Parent require function
80
* @returns YargsInstance for method chaining
81
*/
82
function yargs(processArgs?: string | string[], cwd?: string, parentRequire?: Function): YargsInstance;
83
```
84
85
[Core Parser Configuration](./core-parser.md)
86
87
### Option Definition
88
89
Define and configure command-line options with types, validation, defaults, and relationships between options.
90
91
```javascript { .api }
92
/**
93
* Define a command-line option
94
* @param key - Option name or configuration object
95
* @param opt - Option configuration
96
* @returns YargsInstance for chaining
97
*/
98
option(key: string | Dictionary<OptionDefinition>, opt?: OptionDefinition): YargsInstance;
99
100
/**
101
* Define option aliases
102
* @param key - Option name, array of names, or alias map
103
* @param value - Alias name(s) for the option
104
* @returns YargsInstance for chaining
105
*/
106
alias(key: string | string[] | Dictionary<string | string[]>, value?: string | string[]): YargsInstance;
107
108
/**
109
* Set default values for options
110
* @param key - Option name, array, or defaults object
111
* @param value - Default value
112
* @param defaultDescription - Description of default value
113
* @returns YargsInstance for chaining
114
*/
115
default(key: string | string[] | Dictionary<any>, value?: any, defaultDescription?: string): YargsInstance;
116
```
117
118
[Option Definition](./option-definition.md)
119
120
### Command System
121
122
Define commands, subcommands, and positional arguments with custom handlers and builders.
123
124
```javascript { .api }
125
/**
126
* Define a command with optional subcommands and handlers
127
* @param cmd - Command string, definition object, or array
128
* @param description - Command description
129
* @param builder - Function or object to configure command options
130
* @param handler - Function to execute when command is called
131
* @param middlewares - Array of middleware functions
132
* @param deprecated - Mark command as deprecated
133
* @returns YargsInstance for chaining
134
*/
135
command(
136
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
137
description?: string | boolean,
138
builder?: CommandBuilderDefinition | CommandBuilder,
139
handler?: CommandHandlerCallback,
140
middlewares?: Middleware[],
141
deprecated?: boolean
142
): YargsInstance;
143
144
/**
145
* Define positional argument within a command
146
* @param key - Positional argument name
147
* @param opts - Positional argument configuration
148
* @returns YargsInstance for chaining
149
*/
150
positional(key: string, opts: PositionalDefinition): YargsInstance;
151
```
152
153
[Command System](./command-system.md)
154
155
### Validation and Requirements
156
157
Validate arguments, define required options and commands, and set up option relationships.
158
159
```javascript { .api }
160
/**
161
* Require minimum/maximum number of commands
162
* @param min - Minimum number of commands (default: 1)
163
* @param max - Maximum number of commands
164
* @param minMsg - Message for too few commands
165
* @param maxMsg - Message for too many commands
166
* @returns YargsInstance for chaining
167
*/
168
demandCommand(min?: number, max?: number | string, minMsg?: string | null, maxMsg?: string | null): YargsInstance;
169
170
/**
171
* Make options required
172
* @param keys - Option name(s) or requirements object
173
* @param msg - Error message for missing option
174
* @returns YargsInstance for chaining
175
*/
176
demandOption(keys: string | string[] | Dictionary<string | undefined>, msg?: string): YargsInstance;
177
178
/**
179
* Define conflicting options
180
* @param key1 - First option or conflicts map
181
* @param key2 - Second option name(s)
182
* @returns YargsInstance for chaining
183
*/
184
conflicts(key1: string | Dictionary<string | string[]>, key2?: string | string[]): YargsInstance;
185
```
186
187
[Validation and Requirements](./validation.md)
188
189
### Help and Output
190
191
Configure help system, version information, usage messages, and output formatting.
192
193
```javascript { .api }
194
/**
195
* Configure help option
196
* @param opt - Help option name or false to disable
197
* @param msg - Help option description
198
* @returns YargsInstance for chaining
199
*/
200
help(opt?: string | false, msg?: string): YargsInstance;
201
202
/**
203
* Configure version option
204
* @param opt - Version option name or false to disable
205
* @param msg - Version option description
206
* @param ver - Version string
207
* @returns YargsInstance for chaining
208
*/
209
version(opt?: string | false, msg?: string, ver?: string): YargsInstance;
210
211
/**
212
* Set usage message or define default command
213
* @param msg - Usage message template
214
* @param description - Command description (if defining command)
215
* @param builder - Command builder
216
* @param handler - Command handler
217
* @returns YargsInstance for chaining
218
*/
219
usage(msg: string | null, description?: string | boolean, builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback): YargsInstance;
220
```
221
222
[Help and Output](./help-output.md)
223
224
### Middleware and Processing
225
226
Add custom middleware functions to process arguments during parsing.
227
228
```javascript { .api }
229
/**
230
* Add middleware function to processing pipeline
231
* @param callback - Middleware function to add
232
* @param applyBeforeValidation - Whether to run before validation
233
* @param global - Whether middleware applies globally
234
* @returns YargsInstance for chaining
235
*/
236
middleware(callback: MiddlewareCallback, applyBeforeValidation?: boolean, global?: boolean): YargsInstance;
237
238
/**
239
* Add validation check function
240
* @param f - Validation function
241
* @param global - Whether check applies globally
242
* @returns YargsInstance for chaining
243
*/
244
check(f: CheckCallback, global?: boolean): YargsInstance;
245
```
246
247
### Parsing and Execution
248
249
Parse arguments and execute commands with support for both synchronous and asynchronous operations.
250
251
```javascript { .api }
252
/**
253
* Parse arguments (sync or async based on middleware/handlers)
254
* @param args - Arguments to parse
255
* @param shortCircuit - Context object or callback
256
* @param _parseFn - Parse callback function
257
* @returns Parsed arguments or Promise
258
*/
259
parse(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments | Promise<Arguments>;
260
261
/**
262
* Parse arguments asynchronously
263
* @param args - Arguments to parse
264
* @param shortCircuit - Context object or callback
265
* @param _parseFn - Parse callback function
266
* @returns Promise resolving to parsed arguments
267
*/
268
parseAsync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Promise<Arguments>;
269
270
/**
271
* Parse arguments synchronously (throws if async middleware/handlers used)
272
* @param args - Arguments to parse
273
* @param shortCircuit - Context object or callback
274
* @param _parseFn - Parse callback function
275
* @returns Parsed arguments
276
*/
277
parseSync(args?: string | string[], shortCircuit?: object | ParseCallback | boolean, _parseFn?: ParseCallback): Arguments;
278
```
279
280
[Parsing and Execution](./parsing.md)
281
282
### Helper Functions
283
284
Utility functions for common yargs operations, available from the separate helpers module.
285
286
```javascript { .api }
287
/**
288
* Remove binary name and script name from process.argv
289
* @param argv - Process arguments array (typically process.argv)
290
* @returns Arguments array with binary and script names removed
291
*/
292
function hideBin(argv: string[]): string[];
293
294
/**
295
* Apply configuration extensions and inheritance
296
* @param config - Configuration object to extend
297
* @param cwd - Current working directory
298
* @param mergeExtends - Whether to merge extends deeply
299
* @returns Extended configuration object
300
*/
301
function applyExtends(config: object, cwd: string, mergeExtends?: boolean): object;
302
303
/**
304
* Low-level argument parser (re-exported from yargs-parser)
305
*/
306
const Parser: typeof YargsParser;
307
```
308
309
**Usage Examples:**
310
311
```javascript
312
import yargs from 'yargs';
313
import { hideBin, applyExtends, Parser } from 'yargs/helpers';
314
315
// Most common usage - remove node and script from process.argv
316
const argv = yargs(hideBin(process.argv)).parse();
317
318
// Direct parser usage (advanced)
319
const parsed = Parser(['--port', '3000', '--verbose']);
320
console.log(parsed); // { port: 3000, verbose: true, _: [] }
321
322
// Config extension (typically internal use)
323
const baseConfig = { port: 3000 };
324
const extended = applyExtends(baseConfig, process.cwd());
325
```
326
327
## Global Types
328
329
```javascript { .api }
330
/**
331
* Parsed command-line arguments
332
*/
333
interface Arguments {
334
/** Script name or node command */
335
$0: string;
336
/** Non-option arguments */
337
_: (string | number)[];
338
/** Arguments after the end-of-options flag -- */
339
'--'?: (string | number)[];
340
/** All remaining options */
341
[argName: string]: any;
342
}
343
344
/**
345
* Option definition configuration
346
*/
347
interface OptionDefinition {
348
alias?: string | string[];
349
array?: boolean;
350
boolean?: boolean;
351
choices?: string | string[];
352
coerce?: (arg: any) => any;
353
config?: boolean;
354
configParser?: (configPath: string) => object;
355
conflicts?: string | string[];
356
count?: boolean;
357
default?: any;
358
defaultDescription?: string;
359
deprecate?: string | boolean;
360
deprecated?: string | boolean;
361
desc?: string;
362
describe?: string;
363
description?: string;
364
demand?: string | true;
365
demandOption?: string | true;
366
global?: boolean;
367
group?: string;
368
hidden?: boolean;
369
implies?: string | number | (string | number)[];
370
nargs?: number;
371
normalize?: boolean;
372
number?: boolean;
373
require?: string | true;
374
required?: string | true;
375
requiresArg?: boolean;
376
skipValidation?: boolean;
377
string?: boolean;
378
type?: 'array' | 'boolean' | 'count' | 'number' | 'string';
379
}
380
381
/**
382
* Command handler callback function
383
*/
384
type CommandHandlerCallback = (argv: Arguments) => void | Promise<void>;
385
386
/**
387
* Command builder function
388
*/
389
type CommandBuilder = (yargs: YargsInstance) => YargsInstance | Promise<YargsInstance>;
390
391
/**
392
* Parse callback for handling results
393
*/
394
interface ParseCallback {
395
(err: Error | string | null, argv: Arguments, output: string): void;
396
}
397
398
/**
399
* Middleware callback function
400
*/
401
type MiddlewareCallback = (argv: Arguments, yargs: YargsInstance) => void | Arguments | Promise<void | Arguments>;
402
403
/**
404
* Check callback function
405
*/
406
type CheckCallback = (argv: Arguments, options: Options) => boolean | string | Error | void | Promise<boolean | string | Error | void>;
407
```