0
# Parser Options
1
2
Parser options provide hints and specifications that control how individual arguments are processed and coerced during parsing. These options allow fine-grained control over argument interpretation.
3
4
## Import
5
6
```typescript
7
import parser from "yargs-parser";
8
```
9
10
## API
11
12
```typescript { .api }
13
interface Options {
14
/** An object representing the set of aliases for a key */
15
alias: Dictionary<string | string[]>;
16
/** Indicate that keys should be parsed as an array */
17
array: ArrayOption | ArrayOption[];
18
/** Arguments should be parsed as booleans */
19
boolean: string | string[];
20
/** Indicate a key that represents a path to a configuration file */
21
config: string | string[] | Dictionary<boolean | ConfigCallback>;
22
/** Configuration objects to parse, their properties will be set as arguments */
23
configObjects: Dictionary<any>[];
24
/** Provide configuration options to the yargs-parser */
25
configuration: Partial<Configuration>;
26
/** Provide a custom synchronous function that returns a coerced value from the argument provided */
27
coerce: Dictionary<CoerceCallback>;
28
/** Indicate a key that should be used as a counter */
29
count: string | string[];
30
/** Provide default values for keys */
31
default: Dictionary<any>;
32
/** Environment variables (`process.env`) with the prefix provided should be parsed */
33
envPrefix?: string;
34
/** Specify that a key requires n arguments */
35
narg: Dictionary<number>;
36
/** `path.normalize()` will be applied to values set to this key */
37
normalize: string | string[];
38
/** Keys should be treated as strings (even if they resemble a number) */
39
string: string | string[];
40
/** Keys should be treated as numbers */
41
number: string | string[];
42
/** i18n handler, defaults to util.format */
43
__: (format: any, ...param: any[]) => string;
44
/** Alias lookup table defaults */
45
key: Dictionary<any>;
46
}
47
48
type ArrayOption = string | {
49
key: string;
50
boolean?: boolean;
51
string?: boolean;
52
number?: boolean;
53
integer?: boolean;
54
};
55
56
type CoerceCallback = (arg: any) => any;
57
type ConfigCallback = (configPath: string) => { [key: string]: any } | Error;
58
59
interface Dictionary<T = any> {
60
[key: string]: T;
61
}
62
```
63
64
## Type Specification Options
65
66
### Boolean Options
67
68
Specify which keys should be treated as boolean flags.
69
70
```typescript
71
const result = parser(['--debug', '--verbose', 'false'], {
72
boolean: ['debug', 'verbose']
73
});
74
console.log(result);
75
// Output: { _: [], debug: true, verbose: true }
76
// Note: 'false' is treated as a positional argument, not a boolean value
77
```
78
79
### String Options
80
81
Force keys to be treated as strings, preventing automatic number conversion.
82
83
```typescript
84
const result = parser(['--version', '1.0.0', '--port', '3000'], {
85
string: ['version', 'port']
86
});
87
console.log(result);
88
// Output: { _: [], version: '1.0.0', port: '3000' }
89
// Without string option, port would become number 3000
90
```
91
92
### Number Options
93
94
Force keys to be treated as numbers.
95
96
```typescript
97
const result = parser(['--timeout', '30s', '--count', '042'], {
98
number: ['timeout', 'count']
99
});
100
console.log(result);
101
// Output: { _: [], timeout: NaN, count: 42 }
102
// '30s' cannot be parsed as number, becomes NaN
103
// '042' is parsed as decimal 42, not octal
104
```
105
106
### Array Options
107
108
Specify keys that should be treated as arrays, with optional type coercion.
109
110
```typescript
111
// Simple array specification
112
const simple = parser(['--files', 'a.txt', '--files', 'b.txt'], {
113
array: ['files']
114
});
115
console.log(simple);
116
// Output: { _: [], files: ['a.txt', 'b.txt'] }
117
118
// Array with type specification
119
const typed = parser(['--ports', '3000', '--ports', '4000', '--debug', '--debug'], {
120
array: [
121
{ key: 'ports', number: true },
122
{ key: 'debug', boolean: true }
123
]
124
});
125
console.log(typed);
126
// Output: { _: [], ports: [3000, 4000], debug: [true, true] }
127
```
128
129
## Alias Options
130
131
Define alternative names for options.
132
133
```typescript
134
const result = parser(['-v', '--name', 'Alice', '-p', '8080'], {
135
alias: {
136
verbose: ['v'],
137
name: ['n', 'user'],
138
port: 'p' // Single alias can be string instead of array
139
}
140
});
141
console.log(result);
142
// Output: { _: [], v: true, verbose: true, name: 'Alice', n: 'Alice', user: 'Alice', p: 8080, port: 8080 }
143
```
144
145
## Default Values
146
147
Provide default values for options not specified on command line.
148
149
```typescript
150
const result = parser(['--name', 'Alice'], {
151
default: {
152
port: 3000,
153
debug: false,
154
env: 'development',
155
name: 'Anonymous' // Overridden by command line value
156
}
157
});
158
console.log(result);
159
// Output: { _: [], name: 'Alice', port: 3000, debug: false, env: 'development' }
160
```
161
162
## Advanced Options
163
164
### Count Options
165
166
Specify keys that should count occurrences (like `-vvv` for verbosity levels).
167
168
```typescript
169
const result = parser(['-v', '-v', '-v', '--debug', '--debug'], {
170
count: ['v', 'debug']
171
});
172
console.log(result);
173
// Output: { _: [], v: 3, debug: 2 }
174
```
175
176
### Coerce Options
177
178
Apply custom transformation functions to argument values.
179
180
```typescript
181
const result = parser(['--date', '2023-12-25', '--tags', 'dev,test,prod'], {
182
coerce: {
183
date: (arg: string) => new Date(arg),
184
tags: (arg: string) => arg.split(',')
185
}
186
});
187
console.log(result);
188
// Output: { _: [], date: Date('2023-12-25'), tags: ['dev', 'test', 'prod'] }
189
```
190
191
### Narg Options
192
193
Specify that options should consume multiple following arguments.
194
195
```typescript
196
const result = parser(['--point', '10', '20', '--color', 'red', 'green', 'blue'], {
197
narg: {
198
point: 2,
199
color: 3
200
}
201
});
202
console.log(result);
203
// Output: { _: [], point: [10, 20], color: ['red', 'green', 'blue'] }
204
```
205
206
### Normalize Options
207
208
Apply path normalization to specified keys (Node.js only).
209
210
```typescript
211
const result = parser(['--input', '../docs/./file.txt', '--output', '/tmp//result.txt'], {
212
normalize: ['input', 'output']
213
});
214
console.log(result);
215
// Output: { _: [], input: '../docs/file.txt', output: '/tmp/result.txt' }
216
```
217
218
## Configuration Integration
219
220
Parser options work alongside configuration options:
221
222
```typescript
223
const result = parser(['--foo-bar', '42', '--items', 'a', '--items', 'b'], {
224
string: ['foo-bar'], // Prevent number conversion
225
array: ['items'], // Force array creation
226
configuration: {
227
'camel-case-expansion': true, // Enable camelCase aliases
228
'duplicate-arguments-array': true // Enable array creation for duplicates
229
}
230
});
231
console.log(result);
232
// Output: { _: [], 'foo-bar': '42', fooBar: '42', items: ['a', 'b'] }
233
```
234
235
## Environment Variable Parsing
236
237
Parse environment variables with a specified prefix:
238
239
```typescript
240
// Assuming environment variables: MYAPP_PORT=8080, MYAPP_DEBUG=true
241
const result = parser(['--name', 'test'], {
242
envPrefix: 'MYAPP',
243
boolean: ['debug'],
244
number: ['port']
245
});
246
console.log(result);
247
// Output: { _: [], name: 'test', port: 8080, debug: true }
248
```
249
250
## Configuration File Support
251
252
Load configuration from files:
253
254
```typescript
255
// Basic config file support
256
const result = parser(['--config', 'app.json', '--debug'], {
257
config: ['config'],
258
boolean: ['debug']
259
});
260
261
// Advanced config with custom loader
262
const advanced = parser(['--settings', 'custom.conf'], {
263
config: {
264
settings: (configPath: string) => {
265
// Custom configuration loader
266
const content = fs.readFileSync(configPath, 'utf8');
267
return parseCustomFormat(content);
268
}
269
}
270
});
271
```
272
273
## Configuration Objects
274
275
Provide pre-loaded configuration objects:
276
277
```typescript
278
const result = parser(['--name', 'CLI-value'], {
279
configObjects: [
280
{ port: 3000, debug: true },
281
{ env: 'production', timeout: 30 }
282
],
283
default: {
284
name: 'default-name'
285
}
286
});
287
console.log(result);
288
// Output: { _: [], name: 'CLI-value', port: 3000, debug: true, env: 'production', timeout: 30 }
289
// CLI arguments override config objects, which override defaults
290
```
291
292
## Complex Example
293
294
Combining multiple parser options:
295
296
```typescript
297
const result = parser([
298
'--env', 'production',
299
'--ports', '3000', '--ports', '4000',
300
'-v', '-v',
301
'--database-url', 'postgres://localhost/app',
302
'--feature-flags', 'feature1,feature2'
303
], {
304
alias: {
305
verbose: ['v'],
306
env: ['e'],
307
'database-url': ['db']
308
},
309
array: [
310
{ key: 'ports', number: true }
311
],
312
count: ['verbose'],
313
string: ['env', 'database-url'],
314
coerce: {
315
'feature-flags': (arg: string) => arg.split(',')
316
},
317
default: {
318
env: 'development',
319
verbose: 0,
320
'feature-flags': []
321
},
322
configuration: {
323
'camel-case-expansion': true,
324
'strip-dashed': false
325
}
326
});
327
328
console.log(result);
329
// Complex output with all transformations applied
330
```