0
# Core DevKit API
1
2
Essential programmatic APIs for workspace and project management, providing direct access to Nx's core functionality for building custom tools and plugins.
3
4
## Capabilities
5
6
### Project Graph Operations
7
8
Functions for creating and analyzing the project dependency graph.
9
10
```typescript { .api }
11
/**
12
* Creates the project dependency graph asynchronously
13
* @param opts - Optional configuration for graph creation
14
* @returns Promise resolving to complete project graph
15
*/
16
function createProjectGraphAsync(
17
opts?: { exitOnError?: boolean; resetDaemonClient?: boolean }
18
): Promise<ProjectGraph>;
19
20
/**
21
* Synchronously gets cached project graph (if available)
22
* @returns Current project graph or null if not cached
23
*/
24
function readCachedProjectGraph(): ProjectGraph | null;
25
26
interface ProjectGraph {
27
nodes: Record<string, ProjectGraphProjectNode>;
28
dependencies: Record<string, ProjectGraphDependency[]>;
29
allWorkspaceFiles?: FileMap;
30
}
31
32
interface ProjectGraphProjectNode {
33
name: string;
34
type: ProjectType;
35
data: ProjectGraphProjectNodeData;
36
}
37
38
interface ProjectGraphProjectNodeData {
39
root: string;
40
sourceRoot?: string;
41
targets?: { [targetName: string]: TargetConfiguration };
42
files?: ProjectFileMap;
43
tags?: string[];
44
}
45
46
interface ProjectGraphDependency {
47
source: string;
48
target: string;
49
type: DependencyType;
50
}
51
52
type DependencyType =
53
| 'static'
54
| 'dynamic'
55
| 'implicit'
56
| 'direct'
57
| 'indirect';
58
```
59
60
### Configuration Management
61
62
Functions for reading and updating workspace and project configurations.
63
64
```typescript { .api }
65
/**
66
* Reads the nx.json configuration file from file system
67
* @returns Nx workspace configuration
68
*/
69
function readNxJson(): NxJsonConfiguration;
70
71
/**
72
* Reads the nx.json configuration from a virtual file tree (for generators)
73
* @param tree - Virtual file tree
74
* @returns Nx workspace configuration
75
*/
76
function readNxJson(tree: Tree): NxJsonConfiguration;
77
78
/**
79
* Updates the nx.json configuration file
80
* @param nxJson - Updated configuration object
81
*/
82
function updateNxJson(nxJson: NxJsonConfiguration): void;
83
84
/**
85
* Reads configuration for a specific project
86
* @param projectName - Name of the project
87
* @returns Project configuration
88
*/
89
function readProjectConfiguration(projectName: string): ProjectConfiguration;
90
91
/**
92
* Updates configuration for a specific project
93
* @param projectName - Name of the project
94
* @param config - Updated project configuration
95
*/
96
function updateProjectConfiguration(
97
projectName: string,
98
config: ProjectConfiguration
99
): void;
100
101
/**
102
* Gets all projects in the workspace
103
* @returns Map of project names to configurations
104
*/
105
function getProjects(): Map<string, ProjectConfiguration>;
106
107
/**
108
* Adds a new project configuration to the workspace
109
* @param tree - Virtual file tree (for generators)
110
* @param projectName - Name of the project
111
* @param config - Project configuration
112
*/
113
function addProjectConfiguration(
114
tree: Tree,
115
projectName: string,
116
config: ProjectConfiguration
117
): void;
118
119
/**
120
* Removes a project configuration from the workspace
121
* @param tree - Virtual file tree (for generators)
122
* @param projectName - Name of the project to remove
123
*/
124
function removeProjectConfiguration(tree: Tree, projectName: string): void;
125
126
/**
127
* Gets projects configurations from a project graph
128
* @param projectGraph - Project dependency graph
129
* @returns Projects configurations
130
*/
131
function readProjectsConfigurationFromProjectGraph(
132
projectGraph: ProjectGraph
133
): ProjectsConfigurations;
134
135
interface NxJsonConfiguration {
136
workspaceLayout?: WorkspaceLayout;
137
cli?: CLIOptions;
138
tasksRunnerOptions?: TasksRunnerOptions;
139
namedInputs?: NamedInputs;
140
targetDefaults?: TargetDefaults;
141
generators?: GeneratorOptions;
142
plugins?: PluginConfiguration[];
143
defaultBase?: string;
144
affected?: AffectedOptions;
145
parallel?: number;
146
cacheDirectory?: string;
147
}
148
149
interface WorkspaceLayout {
150
appsDir?: string;
151
libsDir?: string;
152
}
153
154
interface ProjectConfiguration {
155
name?: string;
156
root: string;
157
sourceRoot?: string;
158
projectType?: ProjectType;
159
targets?: { [targetName: string]: TargetConfiguration };
160
tags?: string[];
161
implicitDependencies?: string[];
162
namedInputs?: NamedInputs;
163
generators?: GeneratorOptions;
164
}
165
166
type ProjectType = 'application' | 'library';
167
```
168
169
### Workspace Utilities
170
171
Core workspace information and utility functions.
172
173
```typescript { .api }
174
/**
175
* Gets the absolute path to the workspace root
176
* @returns Workspace root directory path
177
*/
178
function getWorkspaceRoot(): string;
179
180
/**
181
* Workspace root directory path (constant)
182
*/
183
const workspaceRoot: string;
184
185
/**
186
* Gets workspace configuration including all projects
187
* @returns Complete workspace configuration
188
*/
189
function readWorkspaceConfiguration(): WorkspaceConfiguration;
190
191
/**
192
* Updates workspace configuration
193
* @param config - Updated workspace configuration
194
*/
195
function updateWorkspaceConfiguration(config: WorkspaceConfiguration): void;
196
197
interface WorkspaceConfiguration {
198
version: number;
199
projects: Record<string, ProjectConfiguration>;
200
}
201
202
interface ProjectsConfigurations {
203
version: number;
204
projects: Record<string, ProjectConfiguration>;
205
}
206
```
207
208
### Logging and Output
209
210
Utilities for consistent logging and user output.
211
212
```typescript { .api }
213
/**
214
* Logger instance for consistent output formatting
215
*/
216
interface Logger {
217
/** Log informational message */
218
info(message: string): void;
219
/** Log warning message */
220
warn(message: string): void;
221
/** Log error message */
222
error(message: string): void;
223
/** Log debug message (only shown in verbose mode) */
224
debug(message: string): void;
225
/** Log message without formatting */
226
log(message: string): void;
227
}
228
229
const logger: Logger;
230
231
/**
232
* Output utilities for formatted console output
233
*/
234
interface Output {
235
/** Log formatted message with title */
236
log(options: { title: string; bodyLines?: string[] }): void;
237
/** Log error message with formatting */
238
error(options: { title: string; bodyLines?: string[] }): void;
239
/** Log warning message with formatting */
240
warn(options: { title: string; bodyLines?: string[] }): void;
241
/** Log success message with formatting */
242
success(options: { title: string; bodyLines?: string[] }): void;
243
/** Log note/info message with formatting */
244
note(options: { title: string; bodyLines?: string[] }): void;
245
}
246
247
const output: Output;
248
```
249
250
### Target and Task Configuration
251
252
Types and utilities for build targets and task configuration.
253
254
```typescript { .api }
255
interface TargetConfiguration {
256
executor: string;
257
outputs?: string[];
258
options?: any;
259
configurations?: { [config: string]: any };
260
defaultConfiguration?: string;
261
dependsOn?: TargetDependency[];
262
inputs?: (InputDefinition | string)[];
263
cache?: boolean;
264
}
265
266
interface TargetDependency {
267
target: string;
268
projects?: string | string[];
269
params?: 'forward' | 'ignore';
270
}
271
272
interface Target {
273
project: string;
274
target: string;
275
configuration?: string;
276
}
277
278
interface InputDefinition {
279
input?: string;
280
fileset?: string;
281
projects?: string | string[];
282
dependencies?: boolean;
283
externalDependencies?: string[];
284
}
285
286
type NamedInputs = Record<string, (InputDefinition | string)[]>;
287
type TargetDefaults = Record<string, Partial<TargetConfiguration>>;
288
```
289
290
### Plugin Configuration Types
291
292
Types for configuring and managing Nx plugins.
293
294
```typescript { .api }
295
interface PluginConfiguration {
296
plugin: string;
297
options?: any;
298
}
299
300
type CreateNodes = (
301
configFilePath: string,
302
options: any,
303
context: CreateNodesContext
304
) => CreateNodesResult;
305
306
interface CreateNodesResult {
307
projects?: Record<
308
string,
309
{
310
name?: string;
311
targets?: Record<string, TargetConfiguration>;
312
metadata?: ProjectMetadata;
313
}
314
>;
315
}
316
317
interface CreateNodesContext {
318
nxJsonConfiguration: NxJsonConfiguration;
319
workspaceRoot: string;
320
configFiles: string[];
321
}
322
```
323
324
## Usage Examples
325
326
### Basic Workspace Analysis
327
328
```typescript
329
import {
330
createProjectGraphAsync,
331
readNxJson,
332
getProjects,
333
logger
334
} from "nx/src/devkit-exports";
335
336
async function analyzeWorkspace() {
337
// Read workspace configuration
338
const nxConfig = readNxJson();
339
logger.info(`Analyzing workspace with ${Object.keys(nxConfig.projects || {}).length} projects`);
340
341
// Get all projects
342
const projects = getProjects();
343
344
// Create project graph for dependency analysis
345
const graph = await createProjectGraphAsync();
346
347
// Find apps vs libraries
348
const apps = Array.from(projects.entries())
349
.filter(([_, config]) => config.projectType === 'application')
350
.map(([name]) => name);
351
352
const libs = Array.from(projects.entries())
353
.filter(([_, config]) => config.projectType === 'library')
354
.map(([name]) => name);
355
356
logger.info(`Found ${apps.length} applications and ${libs.length} libraries`);
357
358
return { projects, graph, apps, libs };
359
}
360
```
361
362
### Project Configuration Management
363
364
```typescript
365
import {
366
readProjectConfiguration,
367
updateProjectConfiguration,
368
logger
369
} from "nx/src/devkit-exports";
370
371
function addTargetToProject(projectName: string, targetName: string, targetConfig: TargetConfiguration) {
372
try {
373
// Read current configuration
374
const projectConfig = readProjectConfiguration(projectName);
375
376
// Add new target
377
const updatedConfig = {
378
...projectConfig,
379
targets: {
380
...projectConfig.targets,
381
[targetName]: targetConfig
382
}
383
};
384
385
// Save updated configuration
386
updateProjectConfiguration(projectName, updatedConfig);
387
logger.info(`Added target '${targetName}' to project '${projectName}'`);
388
389
} catch (error) {
390
logger.error(`Failed to update project '${projectName}': ${error.message}`);
391
}
392
}
393
394
// Usage
395
addTargetToProject('my-app', 'custom-build', {
396
executor: '@nx/webpack:webpack',
397
options: {
398
outputPath: 'dist/my-app',
399
main: 'src/main.ts',
400
tsConfig: 'tsconfig.app.json'
401
},
402
configurations: {
403
production: {
404
optimization: true,
405
sourceMap: false
406
}
407
}
408
});
409
```
410
411
### Dependency Analysis
412
413
```typescript
414
import { createProjectGraphAsync, logger } from "nx/src/devkit-exports";
415
416
async function findProjectDependencies(projectName: string) {
417
const graph = await createProjectGraphAsync();
418
419
// Find direct dependencies
420
const dependencies = graph.dependencies[projectName] || [];
421
const directDeps = dependencies
422
.filter(dep => dep.type === 'static' || dep.type === 'dynamic')
423
.map(dep => dep.target);
424
425
// Find projects that depend on this project
426
const dependents = Object.keys(graph.dependencies)
427
.filter(project =>
428
graph.dependencies[project].some(dep => dep.target === projectName)
429
);
430
431
logger.info(`Project '${projectName}' dependencies:`);
432
logger.info(` Direct: ${directDeps.join(', ')}`);
433
logger.info(` Dependents: ${dependents.join(', ')}`);
434
435
return { dependencies: directDeps, dependents };
436
}
437
```