0
# Command Line and Configuration
1
2
Configuration management and command-line argument parsing for building TypeScript tooling and custom compilers.
3
4
## Capabilities
5
6
### Command Line Parsing
7
8
Parse TypeScript compiler command-line arguments into structured options and file lists.
9
10
```typescript { .api }
11
/**
12
* Parse command line arguments into compiler options and file names
13
* @param commandLine - Array of command line arguments
14
* @param readFile - Optional function to read files
15
* @returns Parsed command line with options, file names, and errors
16
*/
17
function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine;
18
19
/**
20
* Worker function for parsing command line with custom diagnostics
21
* @param diagnostics - Diagnostics array to populate
22
* @param commandLine - Command line arguments
23
* @param readFile - Optional file reading function
24
* @returns Parsed command line
25
*/
26
function parseCommandLineWorker(
27
diagnostics: Diagnostic[],
28
commandLine: readonly string[],
29
readFile?: (path: string) => string | undefined
30
): ParsedCommandLine;
31
32
interface ParsedCommandLine {
33
options: CompilerOptions;
34
typeAcquisition?: TypeAcquisition;
35
fileNames: string[];
36
projectReferences?: readonly ProjectReference[];
37
watchOptions?: WatchOptions;
38
raw?: any;
39
errors: Diagnostic[];
40
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
41
compileOnSave?: boolean;
42
}
43
```
44
45
**Usage Examples:**
46
47
```typescript
48
import * as ts from "typescript";
49
50
// Parse command line arguments
51
const commandLine = [
52
"--target", "ES2020",
53
"--module", "CommonJS",
54
"--strict",
55
"--outDir", "./dist",
56
"src/index.ts",
57
"src/utils.ts"
58
];
59
60
const parsed = ts.parseCommandLine(commandLine);
61
62
if (parsed.errors.length > 0) {
63
console.log("Command line errors:");
64
for (const error of parsed.errors) {
65
console.log(ts.flattenDiagnosticMessageText(error.messageText, "\n"));
66
}
67
} else {
68
console.log("Target:", parsed.options.target);
69
console.log("Module:", parsed.options.module);
70
console.log("Strict:", parsed.options.strict);
71
console.log("Output Directory:", parsed.options.outDir);
72
console.log("Input Files:", parsed.fileNames);
73
}
74
```
75
76
### Configuration File Reading
77
78
Read and parse TypeScript configuration files (tsconfig.json).
79
80
```typescript { .api }
81
/**
82
* Read and parse a configuration file
83
* @param fileName - Path to configuration file
84
* @param readFile - Function to read file content
85
* @returns Configuration object or error
86
*/
87
function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic };
88
89
/**
90
* Parse configuration file JSON text
91
* @param fileName - Configuration file name (for error reporting)
92
* @param jsonText - JSON content to parse
93
* @returns Parsed configuration or error
94
*/
95
function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic };
96
97
/**
98
* Read JSON configuration file with error handling
99
* @param fileName - Path to JSON configuration file
100
* @param readFile - Function to read file content
101
* @returns JSON source file with diagnostics
102
*/
103
function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile & { parseDiagnostics: Diagnostic[] };
104
105
/**
106
* Convert parsed JSON to configuration object
107
* @param sourceFile - Parsed JSON source file
108
* @param errors - Array to collect parsing errors
109
* @returns Configuration object
110
*/
111
function convertToObject(sourceFile: JsonSourceFile, errors: Diagnostic[]): any;
112
```
113
114
**Usage Examples:**
115
116
```typescript
117
import * as ts from "typescript";
118
import * as fs from "fs";
119
120
// Read tsconfig.json file
121
function readTsConfig(configPath: string) {
122
const readFile = (path: string) => {
123
try {
124
return fs.readFileSync(path, 'utf8');
125
} catch {
126
return undefined;
127
}
128
};
129
130
// Read the configuration file
131
const result = ts.readConfigFile(configPath, readFile);
132
133
if (result.error) {
134
console.error("Error reading config file:",
135
ts.flattenDiagnosticMessageText(result.error.messageText, "\n"));
136
return null;
137
}
138
139
// Parse the configuration
140
const parseResult = ts.parseJsonConfigFileContent(
141
result.config,
142
ts.sys,
143
path.dirname(configPath),
144
undefined,
145
configPath
146
);
147
148
if (parseResult.errors.length > 0) {
149
console.error("Configuration errors:");
150
for (const error of parseResult.errors) {
151
console.error(ts.flattenDiagnosticMessageText(error.messageText, "\n"));
152
}
153
}
154
155
return parseResult;
156
}
157
```
158
159
### Configuration File Processing
160
161
Process and validate TypeScript configuration files with full compiler option support.
162
163
```typescript { .api }
164
/**
165
* Parse JSON configuration file content into compiler options
166
* @param json - Parsed JSON configuration object
167
* @param host - Configuration parsing host
168
* @param basePath - Base path for resolving relative paths
169
* @param existingOptions - Existing options to extend
170
* @param configFileName - Configuration file name
171
* @param resolutionStack - Stack for circular reference detection
172
* @param extraFileExtensions - Additional file extensions to recognize
173
* @returns Parsed configuration
174
*/
175
function parseJsonConfigFileContent(
176
json: any,
177
host: ParseConfigHost,
178
basePath: string,
179
existingOptions?: CompilerOptions,
180
configFileName?: string,
181
resolutionStack?: Path[],
182
extraFileExtensions?: readonly FileExtensionInfo[]
183
): ParsedCommandLine;
184
185
/**
186
* Parse JSON source file into configuration
187
* @param sourceFile - JSON source file to parse
188
* @param host - Configuration parsing host
189
* @param basePath - Base path for resolving relative paths
190
* @param existingOptions - Existing options to extend
191
* @param configFileName - Configuration file name
192
* @param resolutionStack - Stack for circular reference detection
193
* @param extraFileExtensions - Additional file extensions
194
* @returns Parsed configuration
195
*/
196
function parseJsonSourceFileConfigFileContent(
197
sourceFile: JsonSourceFile,
198
host: ParseConfigHost,
199
basePath: string,
200
existingOptions?: CompilerOptions,
201
configFileName?: string,
202
resolutionStack?: Path[],
203
extraFileExtensions?: readonly FileExtensionInfo[]
204
): ParsedCommandLine;
205
206
interface ParseConfigHost {
207
useCaseSensitiveFileNames: boolean;
208
readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[];
209
fileExists(path: string): boolean;
210
readFile(path: string): string | undefined;
211
trace?(s: string): void;
212
}
213
```
214
215
### Configuration File Discovery
216
217
Find TypeScript configuration files in directory hierarchies.
218
219
```typescript { .api }
220
/**
221
* Find configuration file by searching up directory tree
222
* @param searchPath - Starting directory path
223
* @param fileExists - Function to check if file exists
224
* @param configName - Configuration file name to search for
225
* @returns Path to configuration file or undefined
226
*/
227
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined;
228
229
/**
230
* Get canonical file name for configuration
231
* @param fileName - File name to canonicalize
232
* @param useCaseSensitiveFileNames - Whether file system is case sensitive
233
* @returns Canonical file name
234
*/
235
function getCanonicalFileName(fileName: string, useCaseSensitiveFileNames: boolean): string;
236
237
/**
238
* Create incremental configuration parsing host
239
* @param system - File system interface
240
* @returns Configuration parsing host
241
*/
242
function createIncrementalConfigHost(system: System): ParseConfigHost;
243
```
244
245
**Usage Examples:**
246
247
```typescript
248
import * as ts from "typescript";
249
import * as path from "path";
250
251
// Find tsconfig.json starting from current directory
252
function findTsConfig(startPath: string = process.cwd()): string | undefined {
253
return ts.findConfigFile(startPath, ts.sys.fileExists, "tsconfig.json");
254
}
255
256
// Complete configuration loading example
257
function loadTypeScriptConfig(projectPath: string) {
258
// Find configuration file
259
const configFile = ts.findConfigFile(projectPath, ts.sys.fileExists);
260
if (!configFile) {
261
throw new Error("Could not find tsconfig.json");
262
}
263
264
// Read and parse configuration
265
const configResult = ts.readConfigFile(configFile, ts.sys.readFile);
266
if (configResult.error) {
267
throw new Error(ts.formatDiagnostic(configResult.error, {
268
getCanonicalFileName: fileName => fileName,
269
getCurrentDirectory: ts.sys.getCurrentDirectory,
270
getNewLine: () => ts.sys.newLine
271
}));
272
}
273
274
// Parse JSON into compiler options
275
const parseResult = ts.parseJsonConfigFileContent(
276
configResult.config,
277
ts.sys,
278
path.dirname(configFile)
279
);
280
281
if (parseResult.errors.length > 0) {
282
const errorMessage = ts.formatDiagnosticsWithColorAndContext(parseResult.errors, {
283
getCanonicalFileName: fileName => fileName,
284
getCurrentDirectory: ts.sys.getCurrentDirectory,
285
getNewLine: () => ts.sys.newLine
286
});
287
throw new Error(errorMessage);
288
}
289
290
return parseResult;
291
}
292
```
293
294
### Option Management
295
296
Manage and validate TypeScript compiler options.
297
298
```typescript { .api }
299
/**
300
* Get compiler option definition by name
301
* @param optionName - Name of the option
302
* @param allowShort - Whether to allow short option names
303
* @returns Option definition or undefined
304
*/
305
function getOptionFromName(optionName: string, allowShort?: boolean): CommandLineOption | undefined;
306
307
/**
308
* Get map of all available compiler options
309
* @returns Map from option names to option definitions
310
*/
311
function getOptionsNameMap(): Map<string, CommandLineOption>;
312
313
/**
314
* Create diagnostic for invalid custom type
315
* @param opt - Option with invalid custom type
316
* @returns Diagnostic for the error
317
*/
318
function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic;
319
320
/**
321
* Convert compiler option value to proper type
322
* @param option - Option definition
323
* @param value - Raw option value
324
* @returns Converted option value
325
*/
326
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[] };
327
328
/**
329
* Get default compiler options
330
* @returns Default compiler options object
331
*/
332
function getDefaultCompilerOptions(): CompilerOptions;
333
```
334
335
### Project References
336
337
Work with TypeScript project references for multi-project builds.
338
339
```typescript { .api }
340
interface ProjectReference {
341
/** Path to referenced project */
342
path: string;
343
/** Whether reference should be prepended to output */
344
prepend?: boolean;
345
/** Whether reference is circular */
346
circular?: boolean;
347
}
348
349
/**
350
* Resolve project references for a configuration
351
* @param projectReferences - Array of project references
352
* @param resolveProjectPath - Function to resolve project paths
353
* @returns Resolved project references
354
*/
355
function resolveProjectReferencePath(ref: ProjectReference): ResolvedProjectReference;
356
357
interface ResolvedProjectReference {
358
commandLine: ParsedCommandLine;
359
sourceFile: SourceFile;
360
references?: readonly (ResolvedProjectReference | undefined)[];
361
}
362
363
/**
364
* Create solution builder for project references
365
* @param host - Solution builder host
366
* @param rootNames - Root project names
367
* @param defaultOptions - Default compiler options
368
* @returns Solution builder instance
369
*/
370
function createSolutionBuilder<T extends BuilderProgram>(
371
host: SolutionBuilderHost<T>,
372
rootNames: readonly string[],
373
defaultOptions: BuildOptions
374
): SolutionBuilder<T>;
375
```
376
377
## Types
378
379
### Compiler Options
380
381
```typescript { .api }
382
interface CompilerOptions {
383
/** Language version target */
384
target?: ScriptTarget;
385
386
/** Module system */
387
module?: ModuleKind;
388
389
/** Library files to include */
390
lib?: string[];
391
392
/** Allow JavaScript files */
393
allowJs?: boolean;
394
395
/** Check JavaScript files */
396
checkJs?: boolean;
397
398
/** Include source maps */
399
sourceMap?: boolean;
400
401
/** Include inline source maps */
402
inlineSourceMap?: boolean;
403
404
/** Output directory */
405
outDir?: string;
406
407
/** Output file */
408
outFile?: string;
409
410
/** Root directory */
411
rootDir?: string;
412
413
/** Remove comments */
414
removeComments?: boolean;
415
416
/** Don't emit output */
417
noEmit?: boolean;
418
419
/** Don't emit on error */
420
noEmitOnError?: boolean;
421
422
/** Enable strict type checking */
423
strict?: boolean;
424
425
/** Enable strict null checks */
426
strictNullChecks?: boolean;
427
428
/** Enable strict function types */
429
strictFunctionTypes?: boolean;
430
431
/** Enable strict property initialization */
432
strictPropertyInitialization?: boolean;
433
434
/** No implicit any */
435
noImplicitAny?: boolean;
436
437
/** No implicit returns */
438
noImplicitReturns?: boolean;
439
440
/** No implicit this */
441
noImplicitThis?: boolean;
442
443
/** No unused locals */
444
noUnusedLocals?: boolean;
445
446
/** No unused parameters */
447
noUnusedParameters?: boolean;
448
449
/** Module resolution strategy */
450
moduleResolution?: ModuleResolutionKind;
451
452
/** Base URL for module resolution */
453
baseUrl?: string;
454
455
/** Path mapping */
456
paths?: MapLike<string[]>;
457
458
/** Root directories */
459
rootDirs?: string[];
460
461
/** Type roots */
462
typeRoots?: string[];
463
464
/** Types to include */
465
types?: string[];
466
467
/** Allow synthetic default imports */
468
allowSyntheticDefaultImports?: boolean;
469
470
/** ES module interop */
471
esModuleInterop?: boolean;
472
473
/** Preserve symlinks */
474
preserveSymlinks?: boolean;
475
476
/** Allow UMD global access */
477
allowUmdGlobalAccess?: boolean;
478
479
/** Source root */
480
sourceRoot?: string;
481
482
/** Map root */
483
mapRoot?: string;
484
485
/** Include source content */
486
inlineSources?: boolean;
487
488
/** Experimental decorators */
489
experimentalDecorators?: boolean;
490
491
/** Emit decorator metadata */
492
emitDecoratorMetadata?: boolean;
493
494
/** Generate declaration files */
495
declaration?: boolean;
496
497
/** Declaration output directory */
498
declarationDir?: string;
499
500
/** Generate declaration maps */
501
declarationMap?: boolean;
502
503
/** Skip library check */
504
skipLibCheck?: boolean;
505
506
/** Skip default library */
507
skipDefaultLibCheck?: boolean;
508
509
/** Composite project */
510
composite?: boolean;
511
512
/** Incremental compilation */
513
incremental?: boolean;
514
515
/** Build info file */
516
tsBuildInfoFile?: string;
517
518
/** Disable size limit */
519
disableSizeLimit?: boolean;
520
521
/** Charset */
522
charset?: string;
523
524
/** New line character */
525
newLine?: NewLineKind;
526
527
/** No error truncation */
528
noErrorTruncation?: boolean;
529
530
/** No lib */
531
noLib?: boolean;
532
533
/** No resolve */
534
noResolve?: boolean;
535
536
/** Suppress excess property errors */
537
suppressExcessPropertyErrors?: boolean;
538
539
/** Suppress implicit any index errors */
540
suppressImplicitAnyIndexErrors?: boolean;
541
542
/** Force consistent casing */
543
forceConsistentCasingInFileNames?: boolean;
544
545
// JSX options
546
jsx?: JsxEmit;
547
jsxFactory?: string;
548
jsxFragmentFactory?: string;
549
jsxImportSource?: string;
550
551
// Watch options
552
watchFile?: WatchFileKind;
553
watchDirectory?: WatchDirectoryKind;
554
fallbackPolling?: PollingWatchKind;
555
synchronousWatchDirectory?: boolean;
556
557
// Advanced options
558
resolveJsonModule?: boolean;
559
isolatedModules?: boolean;
560
verbatimModuleSyntax?: boolean;
561
allowImportingTsExtensions?: boolean;
562
noCheck?: boolean;
563
}
564
565
enum ScriptTarget {
566
ES3 = 0,
567
ES5 = 1,
568
ES2015 = 2,
569
ES2016 = 3,
570
ES2017 = 4,
571
ES2018 = 5,
572
ES2019 = 6,
573
ES2020 = 7,
574
ES2021 = 8,
575
ES2022 = 9,
576
ESNext = 99,
577
Latest = ESNext
578
}
579
580
enum ModuleKind {
581
None = 0,
582
CommonJS = 1,
583
AMD = 2,
584
UMD = 3,
585
System = 4,
586
ES2015 = 5,
587
ES2020 = 6,
588
ES2022 = 7,
589
ESNext = 99,
590
Node16 = 100,
591
NodeNext = 199
592
}
593
594
enum ModuleResolutionKind {
595
Legacy = 1,
596
Node = 2,
597
Node16 = 3,
598
NodeNext = 99
599
}
600
601
enum JsxEmit {
602
None = 0,
603
Preserve = 1,
604
React = 2,
605
ReactNative = 3,
606
ReactJSX = 4,
607
ReactJSXDev = 5
608
}
609
```
610
611
### Command Line Option Types
612
613
```typescript { .api }
614
interface CommandLineOption {
615
name: string;
616
type: "string" | "number" | "boolean" | "object" | "list" | Map<string | number, string | number>;
617
isFilePath?: boolean;
618
shortName?: string;
619
description?: DiagnosticMessage;
620
paramType?: DiagnosticMessage;
621
isTSConfigOnly?: boolean;
622
isCommandLineOnly?: boolean;
623
showInSimplifiedHelpView?: boolean;
624
category?: DiagnosticMessage;
625
strictFlag?: true;
626
affectsSourceFile?: true;
627
affectsModuleResolution?: true;
628
affectsBindDiagnostics?: true;
629
affectsSemanticDiagnostics?: true;
630
affectsEmit?: true;
631
}
632
633
interface CommandLineOptionOfCustomType extends CommandLineOption {
634
type: Map<string, string | number>;
635
}
636
637
interface TsConfigOnlyOption extends CommandLineOption {
638
type: "object";
639
elementOptions?: Map<string, CommandLineOption>;
640
}
641
642
interface CommandLineOptionOfListType extends CommandLineOption {
643
type: "list";
644
element: CommandLineOption;
645
}
646
647
type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
648
```
649
650
### Watch Options
651
652
```typescript { .api }
653
interface WatchOptions {
654
watchFile?: WatchFileKind;
655
watchDirectory?: WatchDirectoryKind;
656
fallbackPolling?: PollingWatchKind;
657
synchronousWatchDirectory?: boolean;
658
excludeDirectories?: string[];
659
excludeFiles?: string[];
660
}
661
662
enum WatchFileKind {
663
FixedPollingInterval = 0,
664
PriorityPollingInterval = 1,
665
DynamicPriorityPolling = 2,
666
UseFsEvents = 3,
667
UseFsEventsOnParentDirectory = 4
668
}
669
670
enum WatchDirectoryKind {
671
UseFsEvents = 0,
672
FixedPollingInterval = 1,
673
DynamicPriorityPolling = 2
674
}
675
676
enum PollingWatchKind {
677
FixedInterval = 0,
678
PriorityInterval = 1,
679
DynamicPriority = 2
680
}
681
682
interface TypeAcquisition {
683
enable?: boolean;
684
include?: string[];
685
exclude?: string[];
686
disableFilenameBasedTypeAcquisition?: boolean;
687
}
688
```