ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
74 lines (53 loc) • 1.72 kB
Markdown
---
title: Adding Source Files
---
You will need to populate the `ast` object with source files.
Specify as many file globs or file paths as you wish:
```typescript
ast.addExistingSourceFiles("folder/**/*{.d.ts,.ts}");
ast.addExistingSourceFiles("otherFolder/file.ts", "specifyAnotherFile.ts", "orAnotherGlob/**/*.ts");
```
```typescript
const sourceFile = ast.addExistingSourceFile("path/to/file.ts"); // or addSourceFileIfExists
```
Create source files based on an object that looks like the AST of a source file:
```typescript
const sourceFile = ast.createSourceFile("path/to/myStructureFile.ts", {
enums: [{
name: "MyEnum",
members: [{
name: "member"
}]
}],
classes: [{
name: "MyClass",
// etc...
}]
// etc...
});
```
The above would create a source file with the following text:
```typescript
enum MyEnum {
member
}
class MyClass {
}
```
Note: The file will not be created and saved to the file system until calling `.save()` on the source file.
```typescript
const fileText = "enum MyEnum {\n}\n";
const sourceFile = ast.createSourceFile("path/to/myNewFile.ts", fileText);
```
Note: The file will not be created and saved to the file system until calling `.save()` on the source file.
Adding source files to the AST from a structure or text will act like any other source file, but they will not be saved to the disk unless you ask it to be.
```typescript
// save it to the disk if you wish:
sourceFile.save(); // or saveSync();
```