TypeScript compiler wrapper for static analysis and code manipulation.
npx @tessl/cli install tessl/npm-ts-morph@26.0.00
# ts-morph
1
2
ts-morph is a TypeScript compiler wrapper that provides an easier and more intuitive way to programmatically navigate, analyze, and manipulate TypeScript and JavaScript Abstract Syntax Trees (AST). It abstracts the complexities of the native TypeScript compiler API, offering a fluent, chainable interface for code analysis, transformation, and generation tasks.
3
4
## Package Information
5
6
- **Package Name**: ts-morph
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install ts-morph`
10
11
## Core Imports
12
13
```typescript
14
import { Project, SourceFile, ClassDeclaration, Node } from "ts-morph";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { Project, SourceFile, ClassDeclaration, Node } = require("ts-morph");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { Project } from "ts-morph";
27
28
// Create a new project
29
const project = new Project({
30
tsConfigFilePath: "tsconfig.json",
31
});
32
33
// Add a source file
34
const sourceFile = project.createSourceFile("example.ts", `
35
class Example {
36
private name: string;
37
38
constructor(name: string) {
39
this.name = name;
40
}
41
42
greet() {
43
return \`Hello, \${this.name}!\`;
44
}
45
}
46
`);
47
48
// Navigate and manipulate the AST
49
const classDeclaration = sourceFile.getClassOrThrow("Example");
50
const greetMethod = classDeclaration.getMethodOrThrow("greet");
51
52
// Add a parameter to the greet method
53
greetMethod.addParameter({
54
name: "suffix",
55
type: "string",
56
hasQuestionToken: true,
57
});
58
59
// Get the modified code
60
console.log(sourceFile.getFullText());
61
62
// Save the changes
63
project.saveSync();
64
```
65
66
## Architecture
67
68
ts-morph is built around several key components:
69
70
- **Project Management**: The `Project` class manages TypeScript projects, source files, and compilation
71
- **AST Node Wrappers**: Comprehensive set of wrapper classes for every TypeScript AST node type
72
- **Fluent Interface**: Chainable methods for navigation, analysis, and manipulation
73
- **Type System Integration**: Direct access to TypeScript's type checker and type information
74
- **Code Generation**: Structure-based API for creating new code elements
75
- **File System Integration**: Built-in file system operations and directory management
76
77
## Capabilities
78
79
### Project Management
80
81
Core project functionality for managing TypeScript projects, source files, and compilation settings. Essential for setting up analysis and manipulation workflows.
82
83
```typescript { .api }
84
class Project {
85
constructor(options?: ProjectOptions);
86
addSourceFileAtPath(filePath: string): SourceFile;
87
createSourceFile(filePath: string, text?: string, options?: SourceFileCreateOptions): SourceFile;
88
getSourceFile(fileNameOrPath: string): SourceFile | undefined;
89
getSourceFiles(): SourceFile[];
90
save(): Promise<void>;
91
saveSync(): void;
92
emit(): Promise<EmitResult>;
93
emitSync(): EmitResult;
94
getProgram(): Program;
95
getTypeChecker(): TypeChecker;
96
}
97
98
interface ProjectOptions {
99
tsConfigFilePath?: string;
100
compilerOptions?: CompilerOptions;
101
fileSystem?: FileSystemHost;
102
manipulationSettings?: Partial<ManipulationSettings>;
103
useInMemoryFileSystem?: boolean;
104
}
105
```
106
107
[Project Management](./project-management.md)
108
109
### AST Navigation and Manipulation
110
111
Complete set of AST node classes providing navigation, analysis, and manipulation capabilities for all TypeScript language constructs.
112
113
```typescript { .api }
114
abstract class Node<T = ts.Node> {
115
getKind(): SyntaxKind;
116
getKindName(): string;
117
getText(): string;
118
getFullText(): string;
119
getStart(): number;
120
getEnd(): number;
121
getParent(): Node | undefined;
122
getChildren(): Node[];
123
getFirstChild(): Node | undefined;
124
getLastChild(): Node | undefined;
125
getPreviousSibling(): Node | undefined;
126
getNextSibling(): Node | undefined;
127
remove(): void;
128
replaceWithText(text: string): Node;
129
}
130
```
131
132
[AST Nodes](./ast-nodes.md)
133
134
### Code Generation
135
136
Structure-based API for creating new TypeScript code elements with full type safety and intelligent formatting.
137
138
```typescript { .api }
139
interface ClassDeclarationStructure {
140
kind: StructureKind.Class;
141
name: string;
142
extends?: string;
143
implements?: string[];
144
isAbstract?: boolean;
145
isExported?: boolean;
146
decorators?: DecoratorStructure[];
147
docs?: JSDocStructure[];
148
methods?: MethodDeclarationStructure[];
149
properties?: PropertyDeclarationStructure[];
150
constructors?: ConstructorDeclarationStructure[];
151
}
152
153
class SourceFile {
154
addClass(structure: ClassDeclarationStructure): ClassDeclaration;
155
addFunction(structure: FunctionDeclarationStructure): FunctionDeclaration;
156
addInterface(structure: InterfaceDeclarationStructure): InterfaceDeclaration;
157
addEnum(structure: EnumDeclarationStructure): EnumDeclaration;
158
addImportDeclaration(structure: ImportDeclarationStructure): ImportDeclaration;
159
}
160
```
161
162
[Code Generation](./code-generation.md)
163
164
### Type System Integration
165
166
Direct access to TypeScript's type checker and type information for advanced static analysis and type-aware transformations.
167
168
```typescript { .api }
169
class TypeChecker {
170
getTypeAtLocation(node: Node): Type;
171
getSymbolAtLocation(node: Node): Symbol | undefined;
172
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
173
getSignatureFromDeclaration(node: SignatureDeclaration): Signature | undefined;
174
}
175
176
class Type {
177
getText(): string;
178
getSymbol(): Symbol | undefined;
179
getApparentType(): Type;
180
isArray(): boolean;
181
isBoolean(): boolean;
182
isString(): boolean;
183
isNumber(): boolean;
184
isObject(): boolean;
185
isUnion(): boolean;
186
isIntersection(): boolean;
187
}
188
```
189
190
[Type System](./type-system.md)
191
192
### File System Operations
193
194
Comprehensive file system operations and directory management capabilities integrated with the project structure.
195
196
```typescript { .api }
197
class Directory {
198
getName(): string;
199
getPath(): string;
200
getBaseName(): string;
201
getParent(): Directory | undefined;
202
getDirectories(): Directory[];
203
getSourceFiles(): SourceFile[];
204
createDirectory(name: string): Directory;
205
createSourceFile(fileName: string, text?: string): SourceFile;
206
addSourceFileAtPath(filePath: string): SourceFile;
207
copy(dirPath: string, options?: DirectoryCopyOptions): Directory;
208
move(dirPath: string, options?: DirectoryMoveOptions): Directory;
209
delete(): void;
210
}
211
```
212
213
[File System](./file-system.md)
214
215
## Error Handling
216
217
ts-morph provides a comprehensive set of error classes for different error conditions:
218
219
```typescript { .api }
220
class BaseError extends Error {}
221
class ArgumentError extends BaseError {}
222
class FileNotFoundError extends BaseError {}
223
class DirectoryNotFoundError extends BaseError {}
224
class InvalidOperationError extends BaseError {}
225
class ManipulationError extends BaseError {}
226
```
227
228
## Core Types
229
230
```typescript { .api }
231
type Constructor<T = {}> = new (...args: any[]) => T;
232
type WriterFunction = (writer: CodeBlockWriter) => void;
233
234
enum SyntaxKind {
235
// Extensive enumeration of all TypeScript syntax kinds
236
// Re-exported from TypeScript compiler API
237
}
238
239
enum StructureKind {
240
Class,
241
Method,
242
Property,
243
Function,
244
Interface,
245
// ... all structure types
246
}
247
```