Lab 02: Compiler Plugin

Time: 60 minutes | Level: Architect | Docker: node:20-alpine

Overview

TypeScript transformer API: ts.TransformerFactory, ts.visitNode/visitEachChild, custom transform for auto-injecting logging into function calls, ts-patch for compiler plugins, and ts-morph for large-scale code refactoring pipelines.


Step 1: TypeScript Compiler API Overview

// The TypeScript compiler exposes a full AST manipulation API
// Pipeline: Source → Scanner → Parser → AST → Binder → Checker → Emitter

// Key types:
// ts.Node          — base type for all AST nodes
// ts.SourceFile    — root of the AST
// ts.TransformerFactory<T>  — factory returning a transformer
// ts.Transformer<T>         — function: Node → Node
// ts.Visitor               — function: Node → VisitResult

import * as ts from 'typescript';

// Create a minimal transformer factory
const myTransformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
  return (sourceFile) => {
    function visit(node: ts.Node): ts.Node {
      // Transform nodes here
      return ts.visitEachChild(node, visit, context);
    }
    return ts.visitNode(sourceFile, visit) as ts.SourceFile;
  };
};

Step 2: Auto-Inject Logging Transformer


Step 3: Run the Transformer


Step 4: ts-morph — High-Level AST Manipulation


Step 5: ts-morph Code Refactoring Pipeline


Step 6: ts-patch Compiler Plugin


Step 7: Custom Lint-Style Transform


Step 8: Capstone — ts-morph Transformer

(where transform.js mounts the ts-morph script)

📸 Verified Output:


Summary

Tool
API Level
Use Case

ts.TransformerFactory

Raw compiler API

Production transforms

ts.visitNode/visitEachChild

Raw AST traversal

Fine-grained control

ts-morph

High-level wrapper

Codemod scripts

ts-patch

Compiler plugin hook

tsconfig.json integration

AST Explorer

Debugging

Understand node types

tsc --diagnostics

Performance

Find slow type checks

Last updated