ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
56 lines (38 loc) • 1.97 kB
Markdown
title: Manipulating the AST
## Manipulating the AST
Most information about manipulation can be found in the [Details](../details) section. This section only contains general information about manipulation.
### Inserting, replacing, and removing text
In some scenarios, a simple to use API might not have been implemented. If you find that's the case, open an issue on GitHub.
In the meantime, you can insert, replace, and remove text using the following methods, but *generally you will want to avoid using these if possible*:
```typescript
// insert text
sourceFile.insertText(0, "// some comment\n");
// replace text
sourceFile.replaceText([3, 7], "a"); // "// a comment\n"
// remove text
sourceFile.removeText([sourceFile.getPos(), sourceFile.getEnd()]);
```
These methods are also available on any node that has a body (functions, classes, enums, etc.)
#### Writing with `code-block-writer`
It's possible to write text using a provided [code-block-writer](https://github.com/dsherret/code-block-writer):
```typescript
sourceFile.insertText(0, writer => writer.writeLine("let myNumber = 5;")
.write("if (myNumber === 5)").block(() => {
writer.writeLine("console.log('yes')");
}));
```
Using the writer is very useful because it will write code out using the indentation and newline settings of the AST. It's also easier to use.
#### **Warning**
If you use these methods, all previously navigated descendants of the node will be disposed and not be available for use (an exception will be thrown
if you try to use them). You will have to renavigate to those nodes.
For example:
```typescript
let classDeclaration = sourceFile.addClass({ name: "MyClass" });
sourceFile.insertText(0, "// some comment\n");
// this will throw...
classDeclaration.getInstanceProperties();
// you'll need to get the reference again:
classDeclaration = sourceFile.getClass("MyClass")!;
```