{"id":12777,"library":"ts-morph","title":"TypeScript AST Wrapper and Code Manipulator","description":"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.","status":"active","version":"28.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/dsherret/ts-morph","tags":["javascript","typescript","ast","static analysis","code generation","code refactor"],"install":[{"cmd":"npm install ts-morph","lang":"bash","label":"npm"},{"cmd":"yarn add ts-morph","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-morph","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary entry point for creating and managing TypeScript projects.","wrong":"const Project = require('ts-morph').Project;","symbol":"Project","correct":"import { Project } from 'ts-morph';"},{"note":"Used for programmatically defining AST structures like classes, enums, and interfaces.","wrong":"import * as ts from 'ts-morph'; const StructureKind = ts.StructureKind;","symbol":"StructureKind","correct":"import { StructureKind } from 'ts-morph';"},{"note":"The base class for all wrapped TypeScript AST nodes, providing common manipulation and traversal methods.","wrong":"import { SyntaxKind } from 'typescript'; // Not the ts-morph Node class","symbol":"Node","correct":"import { Node } from 'ts-morph';"}],"quickstart":{"code":"import { Project, StructureKind } from \"ts-morph\";\n\nasync function main() {\n  const project = new Project({\n      // Optionally specify compiler options, tsconfig.json, or an in-memory file system.\n      // If initialized with a tsconfig.json, it automatically loads associated source files.\n  });\n\n  // Add source files or create new ones\n  project.addSourceFilesAtPaths(\"src/**/*.ts\");\n  const myClassFile = project.createSourceFile(\"src/MyClass.ts\", \"export class MyClass {}\");\n  const myEnumFile = project.createSourceFile(\"src/MyEnum.ts\", {\n      statements: [{\n          kind: StructureKind.Enum,\n          name: \"MyEnum\",\n          isExported: true,\n          members: [{ name: \"member\" }],\n      }],\n  });\n\n  // Get and manipulate nodes\n  const myClass = myClassFile.getClassOrThrow(\"MyClass\");\n  console.log(myClass.getName()); // \"MyClass\"\n\n  myClass.rename(\"NewName\");\n  myClass.addProperty({\n      name: \"myProp\",\n      initializer: \"5\",\n      has;// Indicates if property should have a question mark (optional) or not\n  });\n\n  // Asynchronously save all changes to the file system\n  await project.save();\n  console.log('Project changes saved.');\n}\n\nmain().catch(console.error);\n","lang":"typescript","description":"Demonstrates initializing a project, adding and creating source files, navigating the AST, manipulating a class, and saving changes."},"warnings":[{"fix":"Always check ts-morph's release notes (e.g., CHANGELOG.md) for its supported TypeScript version before upgrading. Ensure your `typescript` dependency in `package.json` aligns with ts-morph's requirements.","message":"Major versions of ts-morph are typically released to support new TypeScript compiler versions. Upgrading ts-morph often requires upgrading your project's TypeScript version to match its peer dependency, and vice-versa.","severity":"breaking","affected_versions":">=22.0.0"},{"fix":"Review the TypeScript 6.0 release notes (e.g., 'https://devblogs.microsoft.com/typescript/announcing-typescript-6-0/') and ts-morph's breaking changes documentation for specific adjustments needed in your codebase.","message":"Version 28.0.0 introduces support for TypeScript 6.0, which may include breaking changes aligning with the underlying TypeScript API changes.","severity":"breaking","affected_versions":">=28.0.0"},{"fix":"If you chained calls after `forgetDescendants()`, you will need to re-structure your code to explicitly get the node before making subsequent calls, as it no longer returns `this`.","message":"The method `Node.prototype.forgetDescendants()` in ts-morph v22.0.0 and later no longer returns the node itself. It now returns `void`.","severity":"breaking","affected_versions":">=22.0.0"},{"fix":"Upgrade to ts-morph `27.0.2` or higher to resolve browser compatibility issues.","message":"Browser support for ts-morph was temporarily broken in version 26.0.0 due to missing browser fields in its `package.json`, causing issues with modules like `fs/promises` in browser environments.","severity":"gotcha","affected_versions":"26.0.0 - 27.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `ts-morph` is installed (`npm install ts-morph`). If using CommonJS, use `const { Project } = require('ts-morph');`. If using ES modules (recommended), ensure `\"type\": \"module\"` is set in `package.json` or use `.mjs` files.","cause":"The package is not installed, or there's a mismatch between CommonJS `require` and ES module `import` syntax, or an incorrect import path.","error":"Cannot find module 'ts-morph'"},{"fix":"Adjust your project's `typescript` dependency in `package.json` to match the version required by `ts-morph` (check ts-morph's `package.json` or documentation). Then run `npm install`.","cause":"The installed version of `ts-morph` has a peer dependency on a specific TypeScript version, and your project's TypeScript version does not match.","error":"Error: You are using TypeScript X.Y.Z, but ts-morph was built with TypeScript A.B.C."},{"fix":"After significant AST manipulations (e.g., deleting a node, moving files), re-obtain the relevant nodes from the project or their parents. If a node is no longer needed, ensure you don't try to access its properties or methods.","cause":"Attempting to interact with an AST node that has been 'forgotten' (removed from the project's internal AST representation), typically after a manipulation that invalidates the node's position or existence.","error":"InvalidOperationError: The operation is invalid for a node that has been forgotten."}],"ecosystem":"npm"}