TypeScript
ts.createProgram
Learn to create a Program and source files.
What is ts.createProgram?
ts.createProgram is the entry point of a compilation in the TypeScript compiler. The returned Program object bundles source files, compiler options and access to the type checker. It is called with file names, compiler options and an optional CompilerHost.
import ts from "typescript";
const program = ts.createProgram(
["app.ts"],
ts.getDefaultCompilerOptions()
);
const sources = program.getSourceFiles();
From the Program you reach every piece of compilation data — source files, symbols and types.
SourceFile and CompilerHost
Each SourceFile is the root node of the TypeScript AST and has the kind SyntaxKind.SourceFile. Common members are .fileName, .statements and .getText(). Instead of reading from disk you provide a CompilerHost for in-memory sources; its getSourceFile calls ts.createSourceFile.
const host: ts.CompilerHost = {
getSourceFile: (name, lang) =>
ts.createSourceFile(name, code, lang, true),
// ... other methods
};
const program = ts.createProgram(["app.ts"], {}, host);
Exercise Create a program from memory
Use the content const x = 1; for an in-memory app.ts file. Define a CompilerHost whose getSourceFile returns a SourceFile via ts.createSourceFile for that file. Build the program with ts.createProgram and noLib: true, then print the names of the source files.
Show example solution
import ts from "typescript";
const fileName = "app.ts";
const sourceText = "const x = 1;";
const host: ts.CompilerHost = {
fileExists: (name) => name === fileName,
readFile: (name) => (name === fileName ? sourceText : undefined),
getSourceFile: (name, lang) =>
name === fileName ? ts.createSourceFile(name, sourceText, lang, true) : undefined,
writeFile: () => {},
getDefaultLibFileName: () => "lib.d.ts",
useCaseSensitiveFileNames: () => true,
getCanonicalFileName: (n) => n,
getCurrentDirectory: () => "",
getNewLine: () => "\n",
};
const program = ts.createProgram([fileName], { noLib: true }, host);
for (const sf of program.getSourceFiles()) {
console.log(sf.fileName);
}
Test yourself
-
What does the getSourceFiles() method of the Program object return?
- Symbol[] symbols
- A SourceFile[] array
- string[] file names
- Type[] types
Show answer
A SourceFile[] array — getSourceFiles() returns every source file in the compilation as SourceFile nodes, not file names or types.
-
Source file by name
const program = ts.createProgram(["app.ts"], {}, host);
const sf = program.getSourceFile("app.ts");
console.log(sf?.____);
Show answer
const program = ts.createProgram(["app.ts"], {}, host);
const sf = program.getSourceFile("app.ts");
console.log(sf?.fileName);
-
createProgram parts
- ts.createProgram
- Creates the compilation object
- getSourceFiles()
- Returns all source files
- getSourceFile(name)
- Returns a specific file
- CompilerHost
- Customizes file reading
Next lesson: TypeChecker