0
# TypeScript Configuration
1
2
Tools for reading, parsing, and managing TypeScript configuration files across the workspace. These utilities handle tsconfig.json files and provide workspace-aware TypeScript configuration management.
3
4
## Capabilities
5
6
### TypeScript Config Reading
7
8
Read and parse TypeScript configuration files with full compiler options.
9
10
```typescript { .api }
11
/**
12
* Read and parse a TypeScript configuration file
13
* @param tsConfigPath - Path to the tsconfig.json file
14
* @returns Parsed TypeScript configuration with resolved options
15
*/
16
function readTsConfig(tsConfigPath: string): ParsedCommandLine;
17
```
18
19
**Usage Example:**
20
21
```typescript
22
import { readTsConfig } from "@nx/workspace";
23
24
// Read project-specific tsconfig
25
const config = readTsConfig("./apps/my-app/tsconfig.json");
26
console.log("Compiler options:", config.options);
27
console.log("Source files:", config.fileNames);
28
console.log("Project references:", config.projectReferences);
29
30
// Read root workspace tsconfig
31
const rootConfig = readTsConfig("./tsconfig.base.json");
32
console.log("Base paths:", rootConfig.options.baseUrl);
33
console.log("Path mapping:", rootConfig.options.paths);
34
```
35
36
### Root Config Discovery
37
38
Find and manage root TypeScript configuration files in the workspace.
39
40
```typescript { .api }
41
/**
42
* Get root tsconfig path in file tree, preferring tsconfig.base.json
43
* @param tree - The file system tree
44
* @returns Path to root tsconfig or default path
45
*/
46
function getRootTsConfigPathInTree(tree: Tree): string | null;
47
48
/**
49
* Get root tsconfig filename from filesystem
50
* @returns Filename of root tsconfig or null if not found
51
*/
52
function getRootTsConfigFileName(): string | null;
53
```
54
55
**Usage Examples:**
56
57
```typescript
58
import { Tree } from "@nx/devkit";
59
import { getRootTsConfigPathInTree, getRootTsConfigFileName } from "@nx/workspace";
60
61
// In a generator using file tree
62
function myGenerator(tree: Tree) {
63
const rootTsConfig = getRootTsConfigPathInTree(tree);
64
if (rootTsConfig) {
65
console.log("Root tsconfig found at:", rootTsConfig);
66
}
67
}
68
69
// From filesystem
70
const rootConfigFile = getRootTsConfigFileName();
71
if (rootConfigFile) {
72
console.log("Root config file:", rootConfigFile); // "tsconfig.base.json" or "tsconfig.json"
73
}
74
```
75
76
### Relative Path Resolution
77
78
Calculate relative paths to root TypeScript configuration for project references.
79
80
```typescript { .api }
81
/**
82
* Get relative path from target path to root tsconfig
83
* @param tree - The file system tree
84
* @param targetPath - Target path to calculate from
85
* @returns Relative path to root tsconfig
86
*/
87
function getRelativePathToRootTsConfig(tree: Tree, targetPath: string): string;
88
```
89
90
**Usage Example:**
91
92
```typescript
93
import { Tree } from "@nx/devkit";
94
import { getRelativePathToRootTsConfig } from "@nx/workspace";
95
96
function setupProjectTsConfig(tree: Tree, projectPath: string) {
97
const relativePath = getRelativePathToRootTsConfig(tree, projectPath);
98
99
// Create project tsconfig that extends root config
100
const projectTsConfig = {
101
extends: relativePath,
102
compilerOptions: {
103
outDir: "../../dist/out-tsc"
104
},
105
include: ["src/**/*"],
106
exclude: ["src/**/*.spec.ts"]
107
};
108
109
tree.write(`${projectPath}/tsconfig.json`, JSON.stringify(projectTsConfig, null, 2));
110
}
111
```
112
113
### AST Node Discovery
114
115
Find TypeScript AST nodes by syntax kind for advanced code analysis.
116
117
```typescript { .api }
118
/**
119
* Find AST nodes by TypeScript SyntaxKind
120
* @param node - Root AST node to search
121
* @param kind - SyntaxKind or array of SyntaxKinds to find
122
* @param max - Maximum number of nodes to find (default: Infinity)
123
* @returns Array of matching AST nodes
124
*/
125
function findNodes(
126
node: Node,
127
kind: SyntaxKind | SyntaxKind[],
128
max?: number
129
): Node[];
130
```
131
132
**Usage Example:**
133
134
```typescript
135
import { findNodes, readTsConfig } from "@nx/workspace";
136
import { SyntaxKind, createSourceFile, ScriptTarget } from "typescript";
137
138
// Parse TypeScript file and find function declarations
139
const sourceCode = `
140
export function myFunction() {}
141
export class MyClass {}
142
export const myConst = 42;
143
`;
144
145
const sourceFile = createSourceFile(
146
"example.ts",
147
sourceCode,
148
ScriptTarget.Latest
149
);
150
151
// Find all function declarations
152
const functions = findNodes(sourceFile, SyntaxKind.FunctionDeclaration);
153
console.log(`Found ${functions.length} functions`);
154
155
// Find multiple node types
156
const exports = findNodes(sourceFile, [
157
SyntaxKind.FunctionDeclaration,
158
SyntaxKind.ClassDeclaration,
159
SyntaxKind.VariableStatement
160
]);
161
console.log(`Found ${exports.length} export statements`);
162
```
163
164
## Configuration File Management
165
166
### Typical Workspace Structure
167
168
```
169
workspace-root/
170
├── tsconfig.base.json # Root configuration with path mappings
171
├── apps/
172
│ └── my-app/
173
│ ├── tsconfig.json # Extends root, app-specific options
174
│ └── tsconfig.app.json # Build configuration
175
└── libs/
176
└── shared/
177
├── tsconfig.json # Extends root, lib-specific options
178
└── tsconfig.lib.json # Build configuration
179
```
180
181
### Path Mapping Management
182
183
The utilities help manage TypeScript path mappings for monorepo imports:
184
185
```typescript
186
// Root tsconfig.base.json typically contains:
187
{
188
"compilerOptions": {
189
"baseUrl": ".",
190
"paths": {
191
"@my-org/shared": ["libs/shared/src/index.ts"],
192
"@my-org/ui": ["libs/ui/src/index.ts"]
193
}
194
}
195
}
196
```
197
198
## Advanced Usage
199
200
### Custom Config Processing
201
202
```typescript
203
import { readTsConfig } from "@nx/workspace";
204
205
function analyzeProjectConfig(projectPath: string) {
206
const config = readTsConfig(`${projectPath}/tsconfig.json`);
207
208
// Analyze compiler options
209
const hasStrictMode = config.options.strict === true;
210
const targetVersion = config.options.target;
211
212
// Check for custom paths
213
const customPaths = config.options.paths || {};
214
const hasPathMapping = Object.keys(customPaths).length > 0;
215
216
return {
217
strict: hasStrictMode,
218
target: targetVersion,
219
hasPathMappings: hasPathMapping,
220
sourceFiles: config.fileNames.length
221
};
222
}
223
```
224
225
## Types
226
227
```typescript { .api }
228
interface ParsedCommandLine {
229
options: CompilerOptions;
230
fileNames: string[];
231
projectReferences?: ProjectReference[];
232
typeAcquisition?: TypeAcquisition;
233
raw?: any;
234
errors: Diagnostic[];
235
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
236
compileOnSave?: boolean;
237
}
238
239
interface Node {
240
kind: SyntaxKind;
241
getChildren(): Node[];
242
// ... other TypeScript Node properties
243
}
244
245
enum SyntaxKind {
246
FunctionDeclaration,
247
ClassDeclaration,
248
VariableStatement,
249
// ... other TypeScript syntax kinds
250
}
251
```