Custom Transformers and Code Generation
Write compiler transforms that modify the AST.
What Are Transformers?
TypeScript transformers are functions that receive an AST node and return a (possibly modified) node. They run during compilation to generate custom output.
import ts from "typescript";
type Transformer = ts.TransformerFactory<ts.SourceFile>;Transformer Factory Shape
A transformer factory takes a TransformationContext and returns a function that transforms SourceFile nodes.
const myTransformer: ts.TransformerFactory<ts.SourceFile> =
(ctx) => (sf) => {
function visit(node: ts.Node): ts.Node {
// Modify node here
return ts.visitEachChild(node, visit, ctx);
}
return ts.visitNode(sf, visit) as ts.SourceFile;
};All lessons in this course
- Creating a TypeScript Program with the API
- Traversing the AST with Visitors
- Custom Transformers and Code Generation
- Building a Simple Linting Tool