TypeScript compiler wrapper for static analysis and code manipulation.
—
Core project functionality for managing TypeScript projects, source files, and compilation settings. The Project class serves as the main entry point for all ts-morph operations.
The central class for managing TypeScript projects, providing methods for adding source files, managing directories, and performing compilation.
/**
* Main class for managing TypeScript projects
*/
class Project {
/** Create a new project instance */
constructor(options?: ProjectOptions);
/** Add an existing source file to the project */
addSourceFileAtPath(filePath: string): SourceFile;
/** Add an existing source file if it exists, returning undefined if not found */
addSourceFileAtPathIfExists(filePath: string): SourceFile | undefined;
/** Add multiple source files using glob patterns */
addSourceFilesAtPaths(fileGlobs: string | ReadonlyArray<string>): SourceFile[];
/** Create a new source file in the project */
createSourceFile(filePath: string, text?: string, options?: SourceFileCreateOptions): SourceFile;
/** Get a source file by its file name or path */
getSourceFile(fileNameOrPath: string): SourceFile | undefined;
/** Get a source file using a search function */
getSourceFile(searchFunction: (file: SourceFile) => boolean): SourceFile | undefined;
/** Get a source file by its file name or path, throwing if not found */
getSourceFileOrThrow(fileNameOrPath: string): SourceFile;
/** Get a source file using a search function, throwing if not found */
getSourceFileOrThrow(searchFunction: (file: SourceFile) => boolean): SourceFile;
/** Get all source files in the project */
getSourceFiles(): SourceFile[];
/** Get source files matching glob pattern(s) */
getSourceFiles(globPatterns: string | ReadonlyArray<string>): SourceFile[];
/** Add a directory to the project */
addDirectoryAtPath(dirPath: string, options?: DirectoryAddOptions): Directory;
/** Add a directory if it exists, returning undefined if not found */
addDirectoryAtPathIfExists(dirPath: string, options?: DirectoryAddOptions): Directory | undefined;
/** Create a directory in the project */
createDirectory(dirPath: string): Directory;
/** Get a directory by path */
getDirectory(dirPath: string): Directory | undefined;
/** Get a directory by path, throwing if not found */
getDirectoryOrThrow(dirPath: string): Directory;
/** Get all directories in the project */
getDirectories(): Directory[];
/** Save all unsaved source files asynchronously */
save(): Promise<void>;
/** Save all unsaved source files synchronously */
saveSync(): void;
/** Emit TypeScript files to JavaScript asynchronously */
emit(): Promise<EmitResult>;
/** Emit TypeScript files to JavaScript synchronously */
emitSync(): EmitResult;
/** Get the TypeScript program */
getProgram(): Program;
/** Get the TypeScript type checker */
getTypeChecker(): TypeChecker;
/** Get the language service */
getLanguageService(): LanguageService;
/** Get compiler options */
getCompilerOptions(): CompilerOptions;
/** Get pre-emit diagnostics for the project */
getPreEmitDiagnostics(): Diagnostic[];
/** Get configuration file parsing diagnostics */
getConfigFileParsingDiagnostics(): Diagnostic[];
}
interface ProjectOptions {
/** Path to tsconfig.json file */
tsConfigFilePath?: string;
/** Compiler options to use */
compilerOptions?: CompilerOptions;
/** Custom file system host */
fileSystem?: FileSystemHost;
/** Code manipulation settings */
manipulationSettings?: Partial<ManipulationSettings>;
/** Whether to use in-memory file system */
useInMemoryFileSystem?: boolean;
/** Whether to skip adding files from tsconfig.json */
skipAddingFilesFromTsConfig?: boolean;
/** Skip resolving file dependencies when adding files from tsconfig */
skipFileDependencyResolution?: boolean;
/** Skip loading lib files */
skipLoadingLibFiles?: boolean;
/** The folder to use for loading lib files */
libFolderPath?: string;
/** Default compiler options (can be overridden by tsConfigFilePath or compilerOptions) */
defaultCompilerOptions?: CompilerOptions;
/** Creates a resolution host for custom module/type reference directive resolution */
resolutionHost?: ResolutionHostFactory;
}
interface SourceFileCreateOptions {
/** Whether to overwrite if file exists */
overwrite?: boolean;
/** Specifies the script kind of the source file */
scriptKind?: ScriptKind;
}Usage Examples:
import { Project } from "ts-morph";
// Create project with tsconfig.json
const project = new Project({
tsConfigFilePath: "tsconfig.json",
});
// Create project with custom compiler options
const project = new Project({
compilerOptions: {
target: ScriptTarget.ES2020,
module: ModuleKind.ESNext,
strict: true,
},
});
// Add existing files
const sourceFile = project.addSourceFileAtPath("src/example.ts");
// Create new files
const newFile = project.createSourceFile("generated.ts", `
export class Generated {
constructor(public name: string) {}
}
`);
// Work with the project
const files = project.getSourceFiles();
console.log(\`Project has \${files.length} files\`);
// Save changes
await project.save();Result of TypeScript compilation with diagnostic information.
interface EmitResult {
/** Whether the emit was successful */
getEmitSkipped(): boolean;
/** Get compilation diagnostics */
getDiagnostics(): Diagnostic[];
}
interface Diagnostic {
/** Get diagnostic message text */
getMessageText(): string;
/** Get source file where diagnostic occurred */
getSourceFile(): SourceFile | undefined;
/** Get diagnostic category */
getCategory(): DiagnosticCategory;
/** Get diagnostic code */
getCode(): number;
/** Get start position */
getStart(): number | undefined;
/** Get length */
getLength(): number | undefined;
}
enum DiagnosticCategory {
Warning = 0,
Error = 1,
Suggestion = 2,
Message = 3,
}Settings that control how code manipulation operations behave.
interface ManipulationSettings {
/** Indentation text to use */
indentationText: string;
/** New line kind */
newLineKind: NewLineKind;
/** Quote kind for strings */
quoteKind: QuoteKind;
/** Whether to use trailing commas */
useTrailingCommas: boolean;
/** Insert space after opening brace */
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: boolean;
/** Insert space after semicolon */
insertSpaceAfterSemicolonInForStatements: boolean;
/** Insert space before and after binary operators */
insertSpaceBeforeAndAfterBinaryOperators: boolean;
}
enum QuoteKind {
Single = "'",
Double = "\"",
}
enum NewLineKind {
/** \r\n */
CarriageReturnLineFeed = "\r\n",
/** \n */
LineFeed = "\n",
}Utilities for working with TypeScript configuration files.
/**
* Get compiler options from a tsconfig.json file
*/
function getCompilerOptionsFromTsConfig(
filePath: string,
options?: CompilerOptionsFromTsConfigOptions
): CompilerOptionsFromTsConfigResult;
interface CompilerOptionsFromTsConfigOptions {
/** Encoding for reading the file */
encoding?: string;
/** File system host to use */
fileSystem?: FileSystemHost;
}
interface CompilerOptionsFromTsConfigResult {
/** The resolved compiler options */
options: CompilerOptions;
/** Errors encountered while parsing */
errors: Diagnostic[];
}Usage Examples:
import { getCompilerOptionsFromTsConfig } from "ts-morph";
// Parse tsconfig.json
const result = getCompilerOptionsFromTsConfig("./tsconfig.json");
if (result.errors.length > 0) {
console.error("Errors in tsconfig.json:");
result.errors.forEach(error => console.error(error.getMessageText()));
} else {
console.log("Compiler options:", result.options);
}Install with Tessl CLI
npx tessl i tessl/npm-ts-morph