or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

additional-utilities.mdasset-management.mdexecutors.mdgenerators.mdindex.mdpackage-management.mdtypescript-utilities.md

typescript-utilities.mddocs/

0

# TypeScript Utilities

1

2

@nx/js provides comprehensive TypeScript toolchain utilities including compilation, type checking, configuration management, AST manipulation, and transformer loading capabilities.

3

4

## Capabilities

5

6

### Type Checking

7

8

High-performance TypeScript type checking with incremental compilation support and detailed error reporting.

9

10

```typescript { .api }

11

/**

12

* Performs TypeScript type checking with configurable output modes

13

* @param options - Type checking configuration options

14

* @returns Promise resolving to type checking results with errors and file counts

15

*/

16

function runTypeCheck(options: TypeCheckOptions): Promise<TypeCheckResult>;

17

18

/**

19

* Runs type checking in watch mode with continuous monitoring

20

* @param options - Type checking configuration options

21

* @param callback - Callback function for handling type check results

22

* @returns Watch program with close method for cleanup

23

*/

24

function runTypeCheckWatch(

25

options: TypeCheckOptions,

26

callback: Function

27

): { close(): void };

28

29

/**

30

* Formats TypeScript diagnostics for human-readable output

31

* @param ts - TypeScript compiler API instance

32

* @param workspaceRoot - Workspace root directory path

33

* @param diagnostic - TypeScript diagnostic to format

34

* @returns Formatted diagnostic string with file path and message

35

*/

36

function getFormattedDiagnostic(

37

ts: typeof import('typescript'),

38

workspaceRoot: string,

39

diagnostic: Diagnostic

40

): string;

41

42

interface TypeCheckOptions {

43

mode?: 'noEmit' | 'emitDeclarationOnly'; // Type checking mode

44

tsConfigPath: string; // Path to TypeScript configuration

45

workspaceRoot: string; // Workspace root directory

46

incremental?: boolean; // Enable incremental type checking

47

cacheDir?: string; // Cache directory for incremental builds

48

}

49

50

interface TypeCheckResult {

51

warnings: string[]; // Warning messages array

52

errors: string[]; // Error messages array

53

inputFilesCount: number; // Number of input files processed

54

totalFilesCount: number; // Total files in compilation

55

incremental: boolean; // Whether incremental mode was used

56

}

57

58

interface BaseTypeCheckOptions {

59

workspaceRoot: string; // Workspace root directory path

60

tsConfigPath: string; // TypeScript configuration file path

61

}

62

63

interface NoEmitMode extends BaseTypeCheckOptions {

64

mode: 'noEmit'; // No output emission mode

65

}

66

67

interface EmitDeclarationOnlyMode extends BaseTypeCheckOptions {

68

mode: 'emitDeclarationOnly'; // Emit only declaration files

69

outDir: string; // Output directory for declarations

70

}

71

```

72

73

**Usage Examples:**

74

75

```typescript

76

import { runTypeCheck, runTypeCheckWatch } from "@nx/js";

77

78

// Basic type checking

79

const result = await runTypeCheck({

80

mode: 'noEmit',

81

tsConfigPath: 'tsconfig.json',

82

workspaceRoot: process.cwd(),

83

incremental: true

84

});

85

86

if (result.errors.length > 0) {

87

console.error('Type errors found:', result.errors);

88

}

89

90

// Watch mode type checking

91

const watcher = runTypeCheckWatch({

92

mode: 'noEmit',

93

tsConfigPath: 'tsconfig.json',

94

workspaceRoot: process.cwd()

95

}, (result) => {

96

console.log(`Checked ${result.inputFilesCount} files`);

97

});

98

99

// Clean up watcher

100

process.on('SIGINT', () => watcher.close());

101

```

102

103

### TypeScript Configuration

104

105

Comprehensive TypeScript configuration reading, parsing, and path management utilities.

106

107

```typescript { .api }

108

/**

109

* Reads and parses a TypeScript configuration file

110

* @param tsConfigPath - Path to tsconfig.json file

111

* @param sys - Optional TypeScript system interface

112

* @returns Parsed TypeScript command line configuration

113

*/

114

function readTsConfig(tsConfigPath: string, sys?: ts.System): ts.ParsedCommandLine;

115

116

/**

117

* Reads TypeScript configuration from Nx Tree virtual file system

118

* @param tree - Nx Tree instance

119

* @param tsConfigPath - Path to tsconfig.json file

120

* @returns Parsed TypeScript command line configuration

121

*/

122

function readTsConfigFromTree(tree: Tree, tsConfigPath: string): ts.ParsedCommandLine;

123

124

/**

125

* Gets the root TypeScript configuration file path within Tree

126

* @param tree - Nx Tree instance

127

* @returns Root tsconfig path or null if not found

128

*/

129

function getRootTsConfigPathInTree(tree: Tree): string | null;

130

131

/**

132

* Gets relative path from target to root TypeScript configuration

133

* @param tree - Nx Tree instance

134

* @param targetPath - Target directory path

135

* @returns Relative path to root tsconfig

136

*/

137

function getRelativePathToRootTsConfig(tree: Tree, targetPath: string): string;

138

139

/**

140

* Gets the root TypeScript configuration file path

141

* @returns Root tsconfig path or null if not found

142

*/

143

function getRootTsConfigPath(): string | null;

144

145

/**

146

* Gets the root TypeScript configuration filename

147

* @param tree - Optional Nx Tree instance

148

* @returns Root tsconfig filename or null if not found

149

*/

150

function getRootTsConfigFileName(tree?: Tree): string | null;

151

152

/**

153

* Adds path mapping to TypeScript configuration

154

* @param tree - Nx Tree instance

155

* @param importPath - Import path to add

156

* @param lookupPaths - Array of lookup paths for the import

157

*/

158

function addTsConfigPath(tree: Tree, importPath: string, lookupPaths: string[]): void;

159

160

/**

161

* Reads path mappings from TypeScript configuration

162

* @param tsConfig - TypeScript config path or parsed config

163

* @returns Paths object or null if no paths found

164

*/

165

function readTsConfigPaths(tsConfig?: string | ts.ParsedCommandLine): Record<string, string[]> | null;

166

```

167

168

**Usage Examples:**

169

170

```typescript

171

import { readTsConfig, addTsConfigPath, readTsConfigPaths } from "@nx/js";

172

173

// Read TypeScript configuration

174

const config = readTsConfig('tsconfig.json');

175

console.log('Compiler options:', config.options);

176

177

// Add path mapping

178

addTsConfigPath(tree, '@myorg/utils', ['libs/utils/src/index.ts']);

179

180

// Read existing path mappings

181

const paths = readTsConfigPaths('tsconfig.json');

182

console.log('Path mappings:', paths);

183

```

184

185

### TypeScript Configuration Creation

186

187

Utilities for creating and extracting base TypeScript configurations.

188

189

```typescript { .api }

190

/**

191

* Default TypeScript compiler options for Nx projects

192

*/

193

const tsConfigBaseOptions: ts.CompilerOptions;

194

195

/**

196

* Extracts base TypeScript configuration from workspace

197

* @param host - Nx Tree instance

198

* @returns Base TypeScript configuration object

199

*/

200

function extractTsConfigBase(host: Tree): { compilerOptions: ts.CompilerOptions };

201

```

202

203

**Usage Example:**

204

205

```typescript

206

import { tsConfigBaseOptions, extractTsConfigBase } from "@nx/js";

207

208

// Use default options

209

const defaultOptions = tsConfigBaseOptions;

210

211

// Extract from existing configuration

212

const baseConfig = extractTsConfigBase(tree);

213

```

214

215

### AST Manipulation

216

217

Powerful TypeScript AST manipulation utilities for code transformations and modifications.

218

219

```typescript { .api }

220

/**

221

* Resolves module path by import statement

222

* @param importExpr - Import expression string

223

* @param filePath - File path containing the import

224

* @param tsConfigPath - TypeScript configuration file path

225

* @returns Resolved module path or undefined if not found

226

*/

227

function resolveModuleByImport(

228

importExpr: string,

229

filePath: string,

230

tsConfigPath: string

231

): string | undefined;

232

233

/**

234

* Inserts code at specified position in source file

235

* @param host - Nx Tree instance

236

* @param sourceFile - TypeScript source file

237

* @param filePath - File path for the source file

238

* @param insertPosition - Position to insert at

239

* @param contentToInsert - Content to insert

240

* @returns Updated TypeScript source file

241

*/

242

function insertChange(

243

host: Tree,

244

sourceFile: ts.SourceFile,

245

filePath: string,

246

insertPosition: number,

247

contentToInsert: string

248

): ts.SourceFile;

249

250

/**

251

* Replaces content at specified position in source file

252

* @param host - Nx Tree instance

253

* @param sourceFile - TypeScript source file

254

* @param filePath - File path for the source file

255

* @param insertPosition - Position to replace at

256

* @param contentToInsert - New content to insert

257

* @param oldContent - Old content to replace

258

* @returns Updated TypeScript source file

259

*/

260

function replaceChange(

261

host: Tree,

262

sourceFile: ts.SourceFile,

263

filePath: string,

264

insertPosition: number,

265

contentToInsert: string,

266

oldContent: string

267

): ts.SourceFile;

268

269

/**

270

* Removes content at specified position in source file

271

* @param host - Nx Tree instance

272

* @param sourceFile - TypeScript source file

273

* @param filePath - File path for the source file

274

* @param removePosition - Position to remove at

275

* @param contentToRemove - Content to remove

276

* @returns Updated TypeScript source file

277

*/

278

function removeChange(

279

host: Tree,

280

sourceFile: ts.SourceFile,

281

filePath: string,

282

removePosition: number,

283

contentToRemove: string

284

): ts.SourceFile;

285

286

/**

287

* Inserts import statement into source file

288

* @param host - Nx Tree instance

289

* @param source - TypeScript source file

290

* @param fileToEdit - File path to edit

291

* @param symbolName - Symbol name to import

292

* @param fileName - Module file name to import from

293

* @param isDefault - Whether this is a default import

294

* @returns Updated TypeScript source file

295

*/

296

function insertImport(

297

host: Tree,

298

source: ts.SourceFile,

299

fileToEdit: string,

300

symbolName: string,

301

fileName: string,

302

isDefault?: boolean

303

): ts.SourceFile;

304

305

/**

306

* Adds global statement to source file

307

* @param host - Nx Tree instance

308

* @param source - TypeScript source file

309

* @param modulePath - Module path for the source file

310

* @param statement - Statement to add

311

* @returns Updated TypeScript source file

312

*/

313

function addGlobal(

314

host: Tree,

315

source: ts.SourceFile,

316

modulePath: string,

317

statement: string

318

): ts.SourceFile;

319

320

/**

321

* Gets import information from source file based on predicate

322

* @param source - TypeScript source file

323

* @param predicate - Predicate function for filtering imports

324

* @returns Array of import information objects

325

*/

326

function getImport(source: ts.SourceFile, predicate: (a: any) => boolean): any[];

327

328

/**

329

* Replaces node value in source file

330

* @param host - Nx Tree instance

331

* @param sourceFile - TypeScript source file

332

* @param modulePath - Module path for the source file

333

* @param node - AST node to replace

334

* @param content - New content for the node

335

* @returns Updated TypeScript source file

336

*/

337

function replaceNodeValue(

338

host: Tree,

339

sourceFile: ts.SourceFile,

340

modulePath: string,

341

node: ts.Node,

342

content: string

343

): ts.SourceFile;

344

345

/**

346

* Adds parameter to class constructor

347

* @param tree - Nx Tree instance

348

* @param source - TypeScript source file

349

* @param modulePath - Module path for the source file

350

* @param opts - Options with className and param details

351

* @returns Updated TypeScript source file

352

*/

353

function addParameterToConstructor(

354

tree: Tree,

355

source: ts.SourceFile,

356

modulePath: string,

357

opts: { className: string; param: string }

358

): ts.SourceFile;

359

360

/**

361

* Adds method to class

362

* @param tree - Nx Tree instance

363

* @param source - TypeScript source file

364

* @param modulePath - Module path for the source file

365

* @param opts - Options with className, methodHeader, and optional body

366

* @returns Updated TypeScript source file

367

*/

368

function addMethod(

369

tree: Tree,

370

source: ts.SourceFile,

371

modulePath: string,

372

opts: { className: string; methodHeader: string; body?: string }

373

): ts.SourceFile;

374

375

/**

376

* Finds class declaration in source file

377

* @param source - TypeScript source file

378

* @param className - Class name to find

379

* @param silent - Whether to suppress errors if not found

380

* @returns Class declaration node

381

*/

382

function findClass(source: ts.SourceFile, className: string, silent?: boolean): ts.ClassDeclaration;

383

384

/**

385

* Finds nodes of specific syntax kinds in AST

386

* @param node - Root AST node to search from

387

* @param kind - Syntax kind or array of kinds to search for

388

* @param max - Maximum number of nodes to return

389

* @returns Array of matching AST nodes

390

*/

391

function findNodes(node: ts.Node, kind: ts.SyntaxKind | ts.SyntaxKind[], max?: number): ts.Node[];

392

```

393

394

**Usage Examples:**

395

396

```typescript

397

import { insertImport, findClass, addMethod, resolveModuleByImport } from "@nx/js";

398

import * as ts from 'typescript';

399

400

// Resolve module import

401

const resolvedPath = resolveModuleByImport(

402

'./utils',

403

'src/main.ts',

404

'tsconfig.json'

405

);

406

407

// Add import to file

408

const sourceFile = ts.createSourceFile('test.ts', sourceCode, ts.ScriptTarget.Latest);

409

const updatedFile = insertImport(

410

tree,

411

sourceFile,

412

'src/test.ts',

413

'helper',

414

'./utils',

415

false

416

);

417

418

// Find and modify class

419

const classNode = findClass(sourceFile, 'MyClass');

420

const withMethod = addMethod(tree, sourceFile, 'src/test.ts', {

421

className: 'MyClass',

422

methodHeader: 'public doSomething(): void',

423

body: 'console.log("Hello World");'

424

});

425

```

426

427

### Source Node Utilities

428

429

Utilities for extracting and working with TypeScript AST nodes.

430

431

```typescript { .api }

432

/**

433

* Gets all AST nodes from a TypeScript source file

434

* @param sourceFile - TypeScript source file

435

* @returns Array of all AST nodes in the source file

436

*/

437

function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[];

438

```

439

440

**Usage Example:**

441

442

```typescript

443

import { getSourceNodes } from "@nx/js";

444

import * as ts from 'typescript';

445

446

const sourceFile = ts.createSourceFile('test.ts', sourceCode, ts.ScriptTarget.Latest);

447

const allNodes = getSourceNodes(sourceFile);

448

console.log(`Found ${allNodes.length} AST nodes`);

449

```

450

451

### Transformer Loading

452

453

Advanced TypeScript transformer plugin loading and configuration system.

454

455

```typescript { .api }

456

/**

457

* Loads TypeScript transformer plugins with configuration

458

* @param plugins - Array of transformer entries (names or configurations)

459

* @param moduleResolver - Optional module resolution function

460

* @returns Object with compiler plugin hooks and plugin detection flag

461

*/

462

function loadTsTransformers(

463

plugins: TransformerEntry[],

464

moduleResolver?: typeof require.resolve

465

): { compilerPluginHooks: CompilerPluginHooks; hasPlugin: boolean; };

466

467

interface TransformerPlugin {

468

name: string; // Transformer plugin name

469

options: Record<string, unknown>; // Plugin configuration options

470

}

471

472

type TransformerEntry = string | TransformerPlugin;

473

474

interface CompilerPlugin {

475

before?(program: ts.Program, options?: any): ts.TransformerFactory<ts.SourceFile>;

476

after?(program: ts.Program, options?: any): ts.TransformerFactory<ts.SourceFile>;

477

afterDeclarations?(program: ts.Program, options?: any): ts.TransformerFactory<ts.SourceFile>;

478

}

479

480

interface CompilerPluginHooks {

481

before: Array<(program: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;

482

after: Array<(program: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;

483

afterDeclarations: Array<(program: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;

484

}

485

```

486

487

**Usage Example:**

488

489

```typescript

490

import { loadTsTransformers } from "@nx/js";

491

492

const transformers = loadTsTransformers([

493

'typescript-transform-paths',

494

{

495

name: 'custom-transformer',

496

options: { customOption: true }

497

}

498

]);

499

500

if (transformers.hasPlugin) {

501

// Use transformers in TypeScript compilation

502

const program = ts.createProgram(fileNames, options);

503

const beforeTransformers = transformers.compilerPluginHooks.before.map(t => t(program));

504

}

505

```

506

507

### Dependency Management

508

509

Utilities for adding TypeScript-related dependencies to projects.

510

511

```typescript { .api }

512

/**

513

* Adds tslib dependencies to package.json

514

* @param tree - Nx Tree instance

515

*/

516

function addTsLibDependencies(tree: Tree): void;

517

```

518

519

**Usage Example:**

520

521

```typescript

522

import { addTsLibDependencies } from "@nx/js";

523

524

// Add tslib dependencies to the project

525

addTsLibDependencies(tree);

526

```

527

528

### Diagnostic Printing

529

530

Utilities for formatting and printing TypeScript diagnostics.

531

532

```typescript { .api }

533

/**

534

* Prints TypeScript diagnostics with formatting

535

* @param errors - Array of error messages

536

* @param warnings - Array of warning messages

537

* @returns Promise that resolves when printing is complete

538

*/

539

function printDiagnostics(errors?: string[], warnings?: string[]): Promise<void>;

540

```

541

542

**Usage Example:**

543

544

```typescript

545

import { printDiagnostics } from "@nx/js";

546

547

const errors = ['Type error: Cannot assign string to number'];

548

const warnings = ['Warning: Unused variable'];

549

550

await printDiagnostics(errors, warnings);

551

```