TypeScript AST Wrapper and Code Manipulator

28.0.0 · active · verified Sun Apr 19

ts-morph (formerly ts-simple-ast) is a robust library that wraps the TypeScript Compiler API, offering a more user-friendly and programmatic way to navigate, analyze, and manipulate TypeScript and JavaScript code. It provides an in-memory file system where all changes are tracked until explicitly saved, allowing for complex refactoring and code generation tasks. The library maintains strong compatibility with recent TypeScript versions, often releasing new major versions shortly after a new TypeScript compiler release. The current stable version is 28.0.0, which supports TypeScript 6.0. Key differentiators include its extensive wrapper API, enabling easy traversal and modification of AST nodes, and its ability to fall back to the raw `compilerNode` when advanced compiler API access is needed, providing full flexibility for complex scenarios.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a project, adding and creating source files, navigating the AST, manipulating a class, and saving changes.

import { Project, StructureKind } from "ts-morph";

async function main() {
  const project = new Project({
      // Optionally specify compiler options, tsconfig.json, or an in-memory file system.
      // If initialized with a tsconfig.json, it automatically loads associated source files.
  });

  // Add source files or create new ones
  project.addSourceFilesAtPaths("src/**/*.ts");
  const myClassFile = project.createSourceFile("src/MyClass.ts", "export class MyClass {}");
  const myEnumFile = project.createSourceFile("src/MyEnum.ts", {
      statements: [{
          kind: StructureKind.Enum,
          name: "MyEnum",
          isExported: true,
          members: [{ name: "member" }],
      }],
  });

  // Get and manipulate nodes
  const myClass = myClassFile.getClassOrThrow("MyClass");
  console.log(myClass.getName()); // "MyClass"

  myClass.rename("NewName");
  myClass.addProperty({
      name: "myProp",
      initializer: "5",
      has;// Indicates if property should have a question mark (optional) or not
  });

  // Asynchronously save all changes to the file system
  await project.save();
  console.log('Project changes saved.');
}

main().catch(console.error);

view raw JSON →