Legacy wrapper providing comprehensive Nx devkit utilities for creating plugins, generators, and executors
npx @tessl/cli install tessl/npm-nrwl--devkit@19.8.00
# @nrwl/devkit
1
2
The @nrwl/devkit package provides a comprehensive toolkit for creating Nx plugins, generators, and executors. This is a legacy package that re-exports the complete API from @nx/devkit, offering utilities for file manipulation, project configuration, workspace management, and plugin development in Nx monorepos.
3
4
## Overview
5
6
@nrwl/devkit serves as the foundational library for extending Nx workspaces with custom functionality. It enables developers to create sophisticated tooling through its comprehensive API surface covering virtual file systems, project management, dependency analysis, and code generation.
7
8
**Key Features:**
9
- **Virtual File System**: Tree-based abstraction for safe file operations during code generation
10
- **Code Generation**: Template-driven generators with powerful substitution and formatting capabilities
11
- **Project Management**: Complete API for reading, writing, and manipulating project configurations
12
- **Task Execution**: Framework for building custom executors that integrate with Nx's task runner
13
- **Plugin Development**: Extensible plugin system for custom workspace integrations
14
- **Dependency Analysis**: Project graph utilities for understanding and manipulating workspace relationships
15
- **Package Management**: Cross-platform package manager detection and dependency management
16
- **Testing Support**: Comprehensive utilities for testing generators and executors
17
18
## Package Information
19
20
- **Package Name**: @nrwl/devkit
21
- **Package Type**: npm
22
- **Language**: TypeScript
23
- **Installation**: `npm install @nrwl/devkit`
24
25
## Core Imports
26
27
```typescript
28
import { Tree, readProjectConfiguration, logger } from "@nrwl/devkit";
29
```
30
31
For CommonJS:
32
33
```javascript
34
const { Tree, readProjectConfiguration, logger } = require("@nrwl/devkit");
35
```
36
37
For testing utilities:
38
39
```typescript
40
import { createTreeWithEmptyWorkspace } from "@nrwl/devkit/testing";
41
```
42
43
## Basic Usage
44
45
```typescript
46
import {
47
Tree,
48
formatFiles,
49
generateFiles,
50
addProjectConfiguration,
51
logger
52
} from "@nrwl/devkit";
53
54
// Example generator function
55
export default async function myGenerator(tree: Tree, options: any) {
56
// Generate files from templates
57
generateFiles(tree, path.join(__dirname, "files"), ".", {
58
...options,
59
template: ""
60
});
61
62
// Add a new project
63
addProjectConfiguration(tree, options.name, {
64
root: `libs/${options.name}`,
65
projectType: "library",
66
targets: {
67
build: {
68
executor: "@nx/js:tsc",
69
options: {
70
outputPath: `dist/libs/${options.name}`
71
}
72
}
73
}
74
});
75
76
// Format generated files
77
await formatFiles(tree);
78
}
79
```
80
81
## Architecture
82
83
The @nrwl/devkit is built around several key architectural components:
84
85
- **Virtual File System**: The `Tree` interface provides a virtual filesystem for reading, writing, and manipulating files during code generation
86
- **Project Configuration**: APIs for managing workspace projects, targets, and dependencies
87
- **Plugin System**: Interfaces and utilities for creating Nx plugins that extend workspace functionality
88
- **Generator Framework**: Tools for creating code generators that scaffold new projects, components, and features
89
- **Executor Framework**: APIs for building custom executors that run build, test, and other tasks
90
- **Project Graph**: Tools for analyzing and manipulating the dependency graph between workspace projects
91
92
## Capabilities
93
94
### Tree & File System Operations
95
96
Core virtual file system for reading, writing, and manipulating files during code generation and workspace modifications.
97
98
```typescript { .api }
99
interface Tree {
100
read(filePath: string): Buffer | null;
101
read(filePath: string, encoding: BufferEncoding): string | null;
102
write(filePath: string, content: Buffer | string): void;
103
exists(filePath: string): boolean;
104
delete(filePath: string): void;
105
rename(from: string, to: string): void;
106
children(dirPath: string): string[];
107
listChanges(): FileChange[];
108
changePermissions(filePath: string, mode: Mode): void;
109
}
110
111
interface FileChange {
112
path: string;
113
type: 'CREATE' | 'UPDATE' | 'DELETE';
114
content?: Buffer;
115
}
116
```
117
118
[Tree & File System](./tree-filesystem.md)
119
120
### Generators & Code Generation
121
122
Tools for creating code generators that scaffold projects, components, and features with template-based file generation.
123
124
```typescript { .api }
125
function formatFiles(tree: Tree): Promise<void>;
126
127
function generateFiles(
128
tree: Tree,
129
srcFolder: string,
130
target: string,
131
substitutions: Record<string, any>
132
): void;
133
134
type Generator<T = any> = (
135
tree: Tree,
136
schema: T
137
) => void | GeneratorCallback | Promise<void | GeneratorCallback>;
138
139
type GeneratorCallback = () => void | Promise<void>;
140
```
141
142
[Generators & Code Generation](./generators.md)
143
144
### Project Configuration Management
145
146
APIs for managing workspace projects, reading and updating project configurations, and handling workspace-level settings.
147
148
```typescript { .api }
149
function addProjectConfiguration(
150
tree: Tree,
151
projectName: string,
152
projectConfiguration: ProjectConfiguration
153
): void;
154
155
function readProjectConfiguration(tree: Tree, projectName: string): ProjectConfiguration;
156
157
function updateProjectConfiguration(
158
tree: Tree,
159
projectName: string,
160
projectConfiguration: ProjectConfiguration
161
): void;
162
163
interface ProjectConfiguration {
164
name?: string;
165
root: string;
166
sourceRoot?: string;
167
projectType?: ProjectType;
168
targets?: Record<string, TargetConfiguration>;
169
tags?: string[];
170
implicitDependencies?: string[];
171
}
172
```
173
174
[Project Configuration](./project-configuration.md)
175
176
### Executors & Task Management
177
178
Framework for building custom executors that run build, test, lint, and other development tasks.
179
180
```typescript { .api }
181
function runExecutor<T = any>(
182
targetDescription: Target,
183
options: T,
184
context: ExecutorContext
185
): Promise<AsyncIterableIterator<{ success: boolean; [key: string]: any }>>;
186
187
type Executor<T = any> = (
188
options: T,
189
context: ExecutorContext
190
) => Promise<{ success: boolean; [key: string]: any }> | AsyncIterableIterator<{ success: boolean; [key: string]: any }>;
191
192
interface ExecutorContext {
193
root: string;
194
cwd: string;
195
workspace: WorkspaceJsonConfiguration;
196
isVerbose: boolean;
197
projectName?: string;
198
targetName?: string;
199
configurationName?: string;
200
}
201
```
202
203
[Executors & Tasks](./executors.md)
204
205
### Project Graph & Dependencies
206
207
Tools for analyzing and manipulating the dependency graph between workspace projects and external packages.
208
209
```typescript { .api }
210
function createProjectGraphAsync(opts?: {
211
exitOnError?: boolean;
212
}): Promise<ProjectGraph>;
213
214
function readCachedProjectGraph(): ProjectGraph;
215
216
interface ProjectGraph {
217
nodes: Record<string, ProjectGraphProjectNode | ProjectGraphExternalNode>;
218
dependencies: Record<string, ProjectGraphDependency[]>;
219
}
220
221
interface ProjectGraphProjectNode {
222
name: string;
223
type: 'app' | 'lib' | 'e2e';
224
data: ProjectConfiguration;
225
}
226
```
227
228
[Project Graph](./project-graph.md)
229
230
### Plugin Development
231
232
Comprehensive plugin system for extending Nx with custom node creation, dependency analysis, and metadata generation.
233
234
```typescript { .api }
235
interface NxPluginV2 {
236
name: string;
237
createNodes?: CreateNodesV2;
238
createDependencies?: CreateDependencies;
239
createMetadata?: CreateMetadata;
240
}
241
242
type CreateNodesV2<T = any> = [
243
projectFilePattern: string,
244
createNodesFunction: CreateNodesFunctionV2<T>
245
];
246
247
type CreateNodesFunctionV2<T = any> = (
248
projectConfigurationFiles: string[],
249
options: T | undefined,
250
context: CreateNodesContextV2
251
) => Promise<CreateNodesResultV2>;
252
```
253
254
[Plugin Development](./plugins.md)
255
256
### JSON Utilities
257
258
Comprehensive JSON handling utilities for both virtual tree operations and filesystem I/O.
259
260
```typescript { .api }
261
function readJson<T = any>(tree: Tree, path: string): T;
262
263
function writeJson<T = any>(tree: Tree, path: string, value: T): void;
264
265
function updateJson<T = any, U = T>(
266
tree: Tree,
267
path: string,
268
updater: (json: T) => U
269
): void;
270
271
function parseJson<T = any>(input: string, options?: JsonParseOptions): T;
272
273
function serializeJson<T = any>(input: T, options?: JsonSerializeOptions): string;
274
```
275
276
[JSON Utilities](./json-utilities.md)
277
278
### Package Management
279
280
Tools for detecting package managers, managing dependencies, and handling package.json operations.
281
282
```typescript { .api }
283
type PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';
284
285
function detectPackageManager(dir?: string): PackageManager;
286
287
function addDependenciesToPackageJson(
288
tree: Tree,
289
dependencies: Record<string, string>,
290
devDependencies: Record<string, string>,
291
packageJsonPath?: string
292
): GeneratorCallback;
293
294
function ensurePackage<T = any>(packageName: string, version: string): T;
295
```
296
297
[Package Management](./package-management.md)
298
299
### String & Path Utilities
300
301
Utility functions for string manipulation, path operations, and code transformations.
302
303
```typescript { .api }
304
function names(name: string): {
305
name: string;
306
className: string;
307
propertyName: string;
308
constantName: string;
309
fileName: string;
310
};
311
312
function joinPathFragments(...fragments: string[]): string;
313
314
function normalizePath(osSpecificPath: string): string;
315
316
function offsetFromRoot(dir: string): string;
317
318
function stripIndents(strings: TemplateStringsArray, ...values: any[]): string;
319
```
320
321
[String & Path Utilities](./string-path-utilities.md)
322
323
### Testing Utilities
324
325
Testing helpers for creating virtual workspaces and file systems for generator and executor testing.
326
327
```typescript { .api }
328
function createTree(): Tree;
329
330
function createTreeWithEmptyWorkspace(): Tree;
331
```
332
333
[Testing Utilities](./testing-utilities.md)
334
335
## Types
336
337
### Core Types
338
339
```typescript { .api }
340
type ProjectType = 'application' | 'library';
341
342
type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex";
343
344
type Mode = string | number;
345
346
interface Target {
347
project: string;
348
target: string;
349
configuration?: string;
350
}
351
352
interface TargetConfiguration<T = any> {
353
executor: string;
354
options?: T;
355
configurations?: Record<string, Partial<T>>;
356
defaultConfiguration?: string;
357
dependsOn?: TargetDependencyConfig[];
358
inputs?: (InputDefinition | string)[];
359
outputs?: string[];
360
cache?: boolean;
361
metadata?: Record<string, any>;
362
}
363
364
interface TargetDependencyConfig {
365
projects?: string[] | string;
366
dependencies?: boolean;
367
target: string;
368
params?: 'ignore' | 'forward';
369
}
370
371
type InputDefinition =
372
| { input: string; projects: string | string[] }
373
| { input: string; dependencies: true }
374
| { input: string }
375
| { fileset: string }
376
| { runtime: string }
377
| { externalDependencies: string[] }
378
| { dependentTasksOutputFiles: string; transitive?: boolean }
379
| { env: string };
380
381
interface NxJsonConfiguration {
382
extends?: string;
383
npmScope?: string;
384
affected?: NxAffectedConfig;
385
implicitDependencies?: Record<string, string[] | '*'>;
386
targetDefaults?: TargetDefaults;
387
cli?: {
388
defaultCollection?: string;
389
packageManager?: PackageManager;
390
};
391
generators?: Record<string, any>;
392
tasksRunnerOptions?: Record<string, any>;
393
namedInputs?: Record<string, (InputDefinition | string)[]>;
394
plugins?: PluginConfiguration[];
395
parallel?: number;
396
cacheDirectory?: string;
397
defaultBase?: string;
398
nxCloudAccessToken?: string;
399
nxCloudEncryptionKey?: string;
400
nxCloudUrl?: string;
401
useDaemonProcess?: boolean;
402
}
403
404
interface NxAffectedConfig {
405
defaultBase?: string;
406
}
407
408
type TargetDefaults = Record<string, Partial<TargetConfiguration>>;
409
410
type PluginConfiguration = string | ExpandedPluginConfiguration;
411
412
interface ExpandedPluginConfiguration<T = unknown> {
413
plugin: string;
414
options?: T;
415
include?: string[];
416
exclude?: string[];
417
}
418
419
type WorkspaceJsonConfiguration = ProjectsConfigurations;
420
421
interface ProjectsConfigurations {
422
version: number;
423
projects: {
424
[projectName: string]: ProjectConfiguration;
425
};
426
}
427
```
428
429
### Project Graph Types
430
431
```typescript { .api }
432
interface ProjectGraphDependency {
433
type: DependencyType | string;
434
target: string;
435
source: string;
436
}
437
438
enum DependencyType {
439
static = 'static',
440
dynamic = 'dynamic',
441
implicit = 'implicit',
442
}
443
444
interface ProjectGraphExternalNode {
445
type: 'npm';
446
name: `npm:${string}`;
447
data: {
448
version: string;
449
packageName: string;
450
hash?: string;
451
};
452
}
453
```
454
455
### Plugin Types
456
457
```typescript { .api }
458
interface CreateNodesContextV2 {
459
readonly nxJsonConfiguration: NxJsonConfiguration;
460
readonly workspaceRoot: string;
461
}
462
463
type CreateNodesResultV2 = Array<
464
readonly [configFileSource: string, result: CreateNodesResult]
465
>;
466
467
interface CreateNodesResult {
468
projects?: Record<string, Optional<ProjectConfiguration, 'root'>>;
469
externalNodes?: Record<string, ProjectGraphExternalNode>;
470
}
471
472
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
473
```
474
475
### JSON Utilities Types
476
477
```typescript { .api }
478
interface JsonParseOptions {
479
expectComments?: boolean;
480
disallowComments?: boolean;
481
allowTrailingComma?: boolean;
482
}
483
484
interface JsonSerializeOptions {
485
spaces?: number;
486
}
487
```