0Pricing
TypeScript Academy · Lesson

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

  1. Creating a TypeScript Program with the API
  2. Traversing the AST with Visitors
  3. Custom Transformers and Code Generation
  4. Building a Simple Linting Tool
← Back to TypeScript Academy