Resolve and parse tsconfig.json files, replicating TypeScript's behavior
npx @tessl/cli install tessl/npm-tsconfig@7.0.00
# TSConfig
1
2
TSConfig is a TypeScript utility library for resolving and parsing `tsconfig.json` files, replicating TypeScript compiler behavior. It provides both synchronous and asynchronous methods for finding, resolving, loading, and parsing TypeScript configuration files with support for recursive resolution up directory trees.
3
4
## Package Information
5
6
- **Package Name**: tsconfig
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install tsconfig`
10
11
## Core Imports
12
13
```typescript
14
import { resolve, resolveSync, find, findSync, load, loadSync, readFile, readFileSync, parse, LoadResult } from "tsconfig";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { resolve, resolveSync, find, findSync, load, loadSync, readFile, readFileSync, parse } = require("tsconfig");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { load, loadSync } from "tsconfig";
27
28
// Asynchronous loading with recursive resolution
29
const result = await load(process.cwd());
30
console.log("Config path:", result.path);
31
console.log("Config:", result.config);
32
33
// Synchronous loading from specific directory
34
const syncResult = loadSync("/path/to/project", "custom-tsconfig.json");
35
console.log("Loaded config:", syncResult.config);
36
37
// Handle missing config gracefully
38
const fallbackResult = await load("/path/without/tsconfig");
39
// Returns default: { config: { files: [], compilerOptions: {} } }
40
```
41
42
## Capabilities
43
44
### Configuration Resolution
45
46
Resolve paths to `tsconfig.json` files using TypeScript's resolution algorithm.
47
48
```typescript { .api }
49
/**
50
* Resolve a configuration file, like TypeScript compiler
51
* @param cwd - Current working directory to start resolution from
52
* @param filename - Optional specific filename or directory to resolve
53
* @returns Promise resolving to file path or void if not found
54
*/
55
function resolve(cwd: string, filename?: string): Promise<string | void>;
56
57
/**
58
* Synchronous version of resolve
59
* @param cwd - Current working directory to start resolution from
60
* @param filename - Optional specific filename or directory to resolve
61
* @returns File path or void if not found
62
*/
63
function resolveSync(cwd: string, filename?: string): string | void;
64
```
65
66
**Usage Examples:**
67
68
```typescript
69
import { resolve, resolveSync } from "tsconfig";
70
71
// Find tsconfig.json recursively from current directory
72
const configPath = await resolve(process.cwd());
73
74
// Resolve specific config file
75
const specificPath = await resolve("/project/root", "tsconfig.build.json");
76
77
// Resolve config in specific directory
78
const dirPath = await resolve("/project/root", "configs");
79
80
// Synchronous resolution
81
const syncPath = resolveSync(process.cwd());
82
```
83
84
### Recursive Configuration Discovery
85
86
Find `tsconfig.json` files by recursively searching up the directory tree.
87
88
```typescript { .api }
89
/**
90
* Recursively find tsconfig.json upward from directory
91
* @param dir - Directory to start search from
92
* @returns Promise resolving to file path or void if not found
93
*/
94
function find(dir: string): Promise<string | void>;
95
96
/**
97
* Synchronous version of find
98
* @param dir - Directory to start search from
99
* @returns File path or void if not found
100
*/
101
function findSync(dir: string): string | void;
102
```
103
104
**Usage Examples:**
105
106
```typescript
107
import { find, findSync } from "tsconfig";
108
109
// Find tsconfig.json starting from current directory
110
const found = await find(process.cwd());
111
112
// Find from specific directory
113
const projectConfig = await find("/deep/nested/project/path");
114
115
// Synchronous find
116
const syncFound = findSync(__dirname);
117
```
118
119
### Configuration Loading and Parsing
120
121
Load and parse `tsconfig.json` files with comprehensive error handling.
122
123
```typescript { .api }
124
/**
125
* Resolve, load and parse tsconfig.json
126
* @param cwd - Current working directory to start resolution from
127
* @param filename - Optional specific filename or directory to resolve
128
* @returns Promise resolving to LoadResult with path and parsed config
129
*/
130
function load(cwd: string, filename?: string): Promise<LoadResult>;
131
132
/**
133
* Synchronous version of load
134
* @param cwd - Current working directory to start resolution from
135
* @param filename - Optional specific filename or directory to resolve
136
* @returns LoadResult with path and parsed config
137
*/
138
function loadSync(cwd: string, filename?: string): LoadResult;
139
140
/**
141
* Read and parse tsconfig.json file contents
142
* @param filename - Path to file to read
143
* @returns Promise resolving to parsed JSON config
144
*/
145
function readFile(filename: string): Promise<any>;
146
147
/**
148
* Synchronous version of readFile
149
* @param filename - Path to file to read
150
* @returns Parsed JSON config
151
*/
152
function readFileSync(filename: string): any;
153
154
/**
155
* Parse tsconfig.json file contents string
156
* @param contents - Raw file contents to parse
157
* @param filename - Filename for error reporting
158
* @returns Parsed JSON object
159
*/
160
function parse(contents: string, filename: string): any;
161
```
162
163
**Usage Examples:**
164
165
```typescript
166
import { load, loadSync, readFile, readFileSync, parse } from "tsconfig";
167
168
// Load with automatic resolution
169
const result = await load(process.cwd());
170
if (result.path) {
171
console.log(`Loaded from: ${result.path}`);
172
console.log(`Compiler options:`, result.config.compilerOptions);
173
}
174
175
// Load specific config file
176
const buildConfig = await load("/project", "tsconfig.build.json");
177
178
// Direct file reading
179
const config = await readFile("/path/to/tsconfig.json");
180
181
// Parse raw content
182
const rawContent = `{
183
"compilerOptions": {
184
"target": "es2020",
185
"module": "commonjs"
186
}
187
}`;
188
const parsed = parse(rawContent, "tsconfig.json");
189
```
190
191
## Types
192
193
```typescript { .api }
194
/**
195
* Result type for load operations
196
*/
197
interface LoadResult {
198
/** Optional path to the resolved tsconfig file */
199
path?: string;
200
/** Parsed configuration object */
201
config: any;
202
}
203
```
204
205
## Error Handling
206
207
The library throws `TypeError` instances for common error conditions:
208
209
- **Non-existent paths**: `"The specified path does not exist: <filename>"`
210
- **Missing configs**: `"Cannot find a tsconfig.json file at the specified directory: ${filename}"`
211
- **Invalid JSON**: Standard JSON parsing errors from malformed configuration files
212
213
## Default Behavior
214
215
When no `tsconfig.json` file is found, `load` and `loadSync` return a default configuration:
216
217
```typescript
218
{
219
path: undefined,
220
config: {
221
files: [],
222
compilerOptions: {}
223
}
224
}
225
```
226
227
## Advanced Features
228
229
### BOM and Comment Handling
230
231
The library automatically handles:
232
- **UTF-8 BOM removal**: Strips byte order marks from file contents
233
- **JSON comment support**: Removes `//` and `/* */` style comments from configuration files
234
- **Empty file support**: Gracefully handles completely empty `tsconfig.json` files
235
236
### TypeScript Compiler Compatibility
237
238
TSConfig replicates the exact resolution behavior of the TypeScript compiler:
239
- Recursive upward directory traversal
240
- Support for both file and directory targets
241
- Consistent error handling and messaging
242
- Standard `tsconfig.json` filename convention