0
# Configuration Management
1
2
Configuration management loads and manages Istanbul settings from files or objects with validation and defaults. The configuration system supports YAML and JSON formats with comprehensive options for instrumentation, reporting, and hooks.
3
4
## Capabilities
5
6
### Configuration Loading
7
8
Load Istanbul configuration from files or objects with validation and default values.
9
10
```javascript { .api }
11
const config = {
12
/**
13
* Loads configuration from a file
14
* @param {string} file - Path to configuration file (.json, .yml, .yaml)
15
* @param {Object} overrides - Optional overrides to merge with loaded config
16
* @returns {Configuration} Configuration instance
17
*/
18
loadFile(file: string, overrides?: Object): Configuration;
19
20
/**
21
* Loads configuration from an object
22
* @param {Object} obj - Configuration object
23
* @param {Object} overrides - Optional overrides to merge with config
24
* @returns {Configuration} Configuration instance
25
*/
26
loadObject(obj: Object, overrides?: Object): Configuration;
27
28
/**
29
* Returns the default configuration object
30
* @returns {Object} Default configuration with all options
31
*/
32
defaultConfig(): Object;
33
};
34
35
/**
36
* Configuration class providing typed access to all Istanbul settings
37
*/
38
class Configuration {
39
constructor(obj: Object, overrides?: Object);
40
41
/** Instrumentation options */
42
instrumentation: InstrumentationOptions;
43
44
/** Reporting options */
45
reporting: ReportingOptions;
46
47
/** Hook options */
48
hooks: HookOptions;
49
50
/** Coverage threshold checking options */
51
check: CheckOptions;
52
}
53
```
54
55
**Usage Examples:**
56
57
```javascript
58
const { config } = require('istanbul');
59
60
// Load configuration from file
61
const cfg1 = config.loadFile('.istanbul.yml');
62
const cfg2 = config.loadFile('coverage-config.json');
63
64
// Load with overrides
65
const cfg3 = config.loadFile('.istanbul.yml', {
66
reporting: { dir: './custom-coverage' }
67
});
68
69
// Load from object
70
const cfg4 = config.loadObject({
71
instrumentation: {
72
'default-excludes': true,
73
excludes: ['**/test/**']
74
},
75
reporting: {
76
print: 'summary',
77
reports: ['text', 'html']
78
}
79
});
80
81
// Get default configuration
82
const defaults = config.defaultConfig();
83
console.log('Default config:', JSON.stringify(defaults, null, 2));
84
```
85
86
### Instrumentation Options
87
88
Configuration options for code instrumentation behavior.
89
90
```javascript { .api }
91
interface InstrumentationOptions {
92
/**
93
* Returns the root directory for instrumentation
94
* @returns {string} Root directory path
95
*/
96
root(): string;
97
98
/**
99
* Returns array of file extensions to instrument
100
* @returns {string[]} File extensions (e.g., ['.js'])
101
*/
102
extensions(): string[];
103
104
/**
105
* Returns whether to use default excludes (node_modules, etc.)
106
* @returns {boolean} True if default excludes should be used
107
*/
108
defaultExcludes(): boolean;
109
110
/**
111
* Returns array of exclude patterns
112
* @param {boolean} excludeTests - Whether to exclude test files
113
* @returns {string[]} Exclude patterns
114
*/
115
excludes(excludeTests?: boolean): string[];
116
117
/**
118
* Returns whether to copy non-JS files to output directory
119
* @returns {boolean} True if non-JS files should be copied
120
*/
121
completeCopy(): boolean;
122
123
/**
124
* Returns whether to embed source code in coverage objects
125
* @returns {boolean} True if source should be embedded
126
*/
127
embedSource(): boolean;
128
129
/**
130
* Returns the global coverage variable name
131
* @returns {string} Coverage variable name
132
*/
133
variable(): string;
134
135
/**
136
* Returns whether output should be compact (minified)
137
* @returns {boolean} True for compact output
138
*/
139
compact(): boolean;
140
141
/**
142
* Returns whether to preserve comments in instrumented code
143
* @returns {boolean} True to preserve comments
144
*/
145
preserveComments(): boolean;
146
147
/**
148
* Returns whether to save baseline coverage file
149
* @returns {boolean} True to save baseline
150
*/
151
saveBaseline(): boolean;
152
153
/**
154
* Returns path for baseline coverage file
155
* @returns {string} Baseline file path
156
*/
157
baselineFile(): string;
158
159
/**
160
* Returns whether code uses ES6 modules
161
* @returns {boolean} True for ES6 module support
162
*/
163
esModules(): boolean;
164
165
/**
166
* Returns whether to include all source files in coverage
167
* @returns {boolean} True to include all sources
168
*/
169
includeAllSources(): boolean;
170
171
/**
172
* Returns whether to include process ID in coverage filename
173
* @returns {boolean} True to include PID
174
*/
175
includePid(): boolean;
176
}
177
```
178
179
**Configuration Example:**
180
181
```yaml
182
# .istanbul.yml
183
instrumentation:
184
default-excludes: true
185
excludes: ['**/test/**', '**/spec/**', '**/*.test.js']
186
embed-source: false
187
variable: '__coverage__'
188
compact: true
189
preserve-comments: false
190
complete-copy: false
191
save-baseline: false
192
baseline-file: './coverage/coverage-baseline.json'
193
include-all-sources: false
194
es-modules: true
195
include-pid: false
196
```
197
198
### Reporting Options
199
200
Configuration options for coverage report generation.
201
202
```javascript { .api }
203
interface ReportingOptions {
204
/**
205
* Returns console print mode
206
* @returns {'summary'|'detail'|'both'|'none'} Print mode
207
*/
208
print(): 'summary' | 'detail' | 'both' | 'none';
209
210
/**
211
* Returns array of report formats to generate
212
* @returns {string[]} Report format names
213
*/
214
reports(): string[];
215
216
/**
217
* Returns report output directory
218
* @returns {string} Output directory path
219
*/
220
dir(): string;
221
222
/**
223
* Returns detailed report configuration
224
* @returns {Object} Report-specific configuration options
225
*/
226
reportConfig(): Object;
227
228
/**
229
* Returns coverage watermark thresholds
230
* @returns {Object} Watermark configuration
231
*/
232
watermarks(): Object;
233
}
234
```
235
236
**Configuration Example:**
237
238
```yaml
239
# .istanbul.yml
240
reporting:
241
print: summary
242
reports: ['text-summary', 'html', 'lcov']
243
dir: ./coverage
244
watermarks:
245
statements: [50, 80]
246
branches: [50, 80]
247
functions: [50, 80]
248
lines: [50, 80]
249
clover:
250
dir: ./coverage
251
file: clover.xml
252
html:
253
verbose: true
254
linkMapper: null
255
lcov:
256
dir: ./coverage
257
file: lcov.info
258
```
259
260
### Hook Options
261
262
Configuration options for runtime instrumentation hooks.
263
264
```javascript { .api }
265
interface HookOptions {
266
/**
267
* Returns whether to hook vm.runInThisContext
268
* @returns {boolean} True to hook runInThisContext
269
*/
270
hookRunInContext(): boolean;
271
272
/**
273
* Returns post-require hook module path
274
* @returns {string|null} Module path or null
275
*/
276
postRequireHook(): string | null;
277
278
/**
279
* Returns whether to handle SIGINT for coverage reporting
280
* @returns {boolean} True to handle SIGINT
281
*/
282
handleSigint(): boolean;
283
}
284
```
285
286
**Configuration Example:**
287
288
```yaml
289
# .istanbul.yml
290
hooks:
291
hook-run-in-context: false
292
post-require-hook: null
293
handle-sigint: true
294
```
295
296
### Coverage Threshold Options
297
298
Configuration options for coverage threshold validation.
299
300
```javascript { .api }
301
interface CheckOptions {
302
/**
303
* Global coverage thresholds that apply to entire codebase
304
*/
305
global: {
306
statements: number; // Global statement coverage threshold (0-100)
307
lines: number; // Global line coverage threshold (0-100)
308
branches: number; // Global branch coverage threshold (0-100)
309
functions: number; // Global function coverage threshold (0-100)
310
excludes: string[]; // File patterns to exclude from global checks
311
};
312
313
/**
314
* Per-file coverage thresholds that apply to each individual file
315
*/
316
each: {
317
statements: number; // Per-file statement coverage threshold (0-100)
318
lines: number; // Per-file line coverage threshold (0-100)
319
branches: number; // Per-file branch coverage threshold (0-100)
320
functions: number; // Per-file function coverage threshold (0-100)
321
excludes: string[]; // File patterns to exclude from per-file checks
322
};
323
}
324
```
325
326
**Configuration Example:**
327
328
```yaml
329
# .istanbul.yml
330
check:
331
global:
332
statements: 80
333
branches: 75
334
functions: 85
335
lines: 80
336
excludes: ['**/test/**']
337
each:
338
statements: 70
339
branches: 65
340
functions: 75
341
lines: 70
342
excludes: ['**/fixtures/**']
343
```
344
345
### Complete Configuration Examples
346
347
#### Basic Configuration (JSON)
348
349
```json
350
{
351
"instrumentation": {
352
"default-excludes": true,
353
"excludes": ["**/test/**", "**/*.test.js"],
354
"embed-source": false,
355
"variable": "__coverage__",
356
"compact": true,
357
"preserve-comments": false
358
},
359
"reporting": {
360
"print": "summary",
361
"reports": ["text", "html", "lcov"],
362
"dir": "./coverage"
363
},
364
"hooks": {
365
"hook-run-in-context": false,
366
"post-require-hook": null,
367
"handle-sigint": true
368
}
369
}
370
```
371
372
#### Advanced Configuration (YAML)
373
374
```yaml
375
instrumentation:
376
default-excludes: true
377
excludes:
378
- '**/test/**'
379
- '**/tests/**'
380
- '**/*.test.js'
381
- '**/*.spec.js'
382
- '**/node_modules/**'
383
embed-source: false
384
variable: '__coverage__'
385
compact: true
386
preserve-comments: false
387
complete-copy: false
388
save-baseline: true
389
baseline-file: './coverage/baseline.json'
390
include-all-sources: true
391
es-modules: true
392
393
reporting:
394
print: both
395
reports: ['text-summary', 'html', 'lcov', 'json-summary']
396
dir: ./coverage
397
watermarks:
398
statements: [70, 90]
399
branches: [60, 85]
400
functions: [75, 95]
401
lines: [70, 90]
402
html:
403
verbose: true
404
subdir: html-report
405
lcov:
406
dir: ./coverage
407
file: coverage.lcov
408
json-summary:
409
file: coverage-summary.json
410
411
hooks:
412
hook-run-in-context: false
413
post-require-hook: './test/coverage-setup.js'
414
handle-sigint: true
415
416
check:
417
global:
418
statements: 85
419
branches: 80
420
functions: 90
421
lines: 85
422
each:
423
statements: 75
424
branches: 70
425
functions: 80
426
lines: 75
427
```
428
429
### Using Configuration Objects
430
431
```javascript
432
const { config, Instrumenter, Reporter } = require('istanbul');
433
434
// Load configuration
435
const cfg = config.loadFile('./.istanbul.yml');
436
437
// Use with instrumenter
438
const instrumenter = new Instrumenter({
439
coverageVariable: cfg.instrumentation.variable(),
440
embedSource: cfg.instrumentation.embedSource(),
441
preserveComments: cfg.instrumentation.preserveComments(),
442
esModules: cfg.instrumentation.esModules()
443
});
444
445
// Use with reporter
446
const reporter = new Reporter(cfg, cfg.reporting.dir());
447
cfg.reporting.reports().forEach(format => {
448
reporter.add(format);
449
});
450
451
// Access specific options
452
console.log('Coverage variable:', cfg.instrumentation.variable());
453
console.log('Report directory:', cfg.reporting.dir());
454
console.log('Exclude patterns:', cfg.instrumentation.excludes());
455
console.log('Report formats:', cfg.reporting.reports());
456
```
457
458
### Configuration Validation
459
460
Istanbul validates configuration options and provides helpful error messages:
461
462
```javascript
463
try {
464
const cfg = config.loadFile('./invalid-config.yml');
465
} catch (error) {
466
console.error('Configuration error:', error.message);
467
// Handle invalid configuration
468
}
469
470
// Check for required values
471
const cfg = config.loadFile('./.istanbul.yml');
472
if (!cfg.reporting.dir()) {
473
throw new Error('Report directory must be configured');
474
}
475
```
476
477
### Environment-Specific Configuration
478
479
Load different configurations based on environment:
480
481
```javascript
482
const environment = process.env.NODE_ENV || 'development';
483
const configFile = `./.istanbul.${environment}.yml`;
484
485
let cfg;
486
try {
487
cfg = config.loadFile(configFile);
488
console.log(`Loaded ${environment} configuration`);
489
} catch (error) {
490
console.log('Loading default configuration');
491
cfg = config.loadFile('./.istanbul.yml');
492
}
493
494
// Override with environment variables
495
const overrides = {};
496
if (process.env.COVERAGE_DIR) {
497
overrides.reporting = { dir: process.env.COVERAGE_DIR };
498
}
499
500
if (Object.keys(overrides).length > 0) {
501
cfg = config.loadObject(cfg, overrides);
502
}
503
```
504
505
### Programmatic Configuration
506
507
Create configuration objects programmatically:
508
509
```javascript
510
const customConfig = {
511
instrumentation: {
512
'default-excludes': true,
513
'excludes': ['**/test/**'],
514
'embed-source': false,
515
'variable': '__coverage__',
516
'es-modules': true
517
},
518
reporting: {
519
'print': 'summary',
520
'reports': ['html', 'lcov'],
521
'dir': './coverage'
522
},
523
hooks: {
524
'hook-run-in-context': false,
525
'handle-sigint': true
526
}
527
};
528
529
const cfg = config.loadObject(customConfig);
530
531
// Merge with overrides
532
const cfg2 = config.loadObject(customConfig, {
533
reporting: { dir: './custom-coverage' }
534
});
535
```