Introduction to ts-morph: What It Is and Why You Need It
\n\nts-morph is a powerful library for programmatic work with the TypeScript Abstract Syntax Tree (AST). It provides a convenient and intuitive API for analyzing, modifying, and generating TypeScript code. Unlike directly using the TypeScript Compiler API, ts-morph offers a higher-level interface that significantly simplifies many routine tasks.
\n\nWhy do you need this library? Imagine you need to:
\n- \n
- Refactor code: Automatically rename all occurrences of a function, change a method signature, or move a class to another file. \n
- Static analysis: Find all unused variables, check compliance with corporate coding standards, or collect metadata about the project structure. \n
- Code generation: Create types based on a JSON schema, generate CRUD operations for a database, or automatically add documentation. \n
- Build developer tools: Write a linter plugin, a custom documentation generator, or a code migration utility. \n
ts-morph abstracts the complexity of the TypeScript Compiler API by providing an object-oriented approach. You work with projects, files, classes, functions, and other code elements as regular objects, rather than low-level AST nodes.
\n\nInstalling ts-morph
\n\nThe library is installed via npm or yarn. It is available as a Node.js package.
\n\nnpm install ts-morph\n\nor, if you use yarn:
\n\nyarn add ts-morph\n\nAfter installation, you can import the library into your project:
\n\nimport { Project } from 'ts-morph';\n\nts-morph requires TypeScript (specified as a peer dependency). Make sure TypeScript is installed in your project:
\n\nnpm install typescript\n\nQuick Start with a Code Example
\n\nLet's write a simple script that creates a new TypeScript file, adds a function to it, and then outputs the generated code.
\n\nimport { Project, SyntaxKind } from 'ts-morph';\n\n// Create a new project\nconst project = new Project({\n useInMemoryFileSystem: true, // Work in memory, without saving to disk\n});\n\n// Create a new file\nconst sourceFile = project.createSourceFile('example.ts', '');\n\n// Add a function\nconst functionDeclaration = sourceFile.addFunction({\n name: 'greet',\n parameters: [{ name: 'name', type: 'string' }],\n returnType: 'string',\n statements: [\n `return \\`Hello, \\${name}!\\`;`,\n ],\n});\n\n// Add a JSDoc comment\nfunctionDeclaration.addJsDoc({\n description: 'Greets the user',\n tags: [{ tagName: 'param', text: 'name - The user\\'s name' }],\n});\n\n// Output the generated code\nconsole.log(sourceFile.getText());\n\n\nScript execution result:
\n\n/**\n * Greets the user\n * @param name - The user's name\n */\nfunction greet(name: string): string {\n return `Hello, ${name}!`;\n}\n\n\nAs you can see, we programmatically created a full function with JSDoc documentation. This is just a small part of ts-morph's capabilities.
\n\nKey Methods and Functions of ts-morph
\n\nLet's look at 10 key library methods with detailed descriptions and examples.
\n\n1. Project.createSourceFile()
\nWhat it does: Creates a new TypeScript source file in the project. The file can be empty or contain initial code.
\nParameters:
\n- \n
filePath: string— path to the file (relative to the project root). \n sourceText?: string— initial file content (optional).
Also in library
Swift QR Code Generator: EFQRCode Library for iOS and macOS
Retrofit for Kotlin: Complete Guide with Examples
Database Migrations in Node.js: Sequelize, Knex and TypeORM
Reactive Programming in JavaScript (Node.js): RxJS & Observables