TypeScript Compiler API
CustomTransformers.before
Runs custom transformations before the built-in JavaScript transformations. This can inspect TypeScript annotations and transform syntax that will subsequently be lowered. It is an emission hook, not a pre-type-check source edit; original program diagnostics do not certify transformed semantics. Scope changes carefully and test output behavior. Baseline: the Node.js API of TypeScript 5.8.3. The examples are CommonJS tooling scripts, not browser or CodeRunner snippets. TypeScript must be installed locally.
Formal Syntax & Structure
typescript syntaxtypescript
customTransformers.before?: (ts.TransformerFactory<ts.SourceFile> | ts.CustomTransformerFactory)[]Working Example
Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const options = { strict: true, types: [], target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, noEmitOnError: true, declaration: true };const program = ts.createProgram(["input.ts"], options);assert.deepEqual(ts.getPreEmitDiagnostics(program).map(d => d.code), []);const fs = require("node:fs");const outputs = new Map();const write = (name, text) => outputs.set(name, text);const replaceSeven = context => root => { function visit(node) { if (ts.isNumericLiteral(node) && node.text === "7") return context.factory.createNumericLiteral(8); return ts.visitEachChild(node, visit, context); } return ts.visitNode(root, visit, ts.isSourceFile);};let sawAnnotation = false;const before = context => root => { sawAnnotation = Boolean(root.statements[0].declarationList.declarations[0].type); return replaceSeven(context)(root);};const result = program.emit(undefined, write, undefined, false, { before: [before] });assert(!result.emitSkipped && sawAnnotation);const js = outputs.get("input.js");assert(js.includes("exports.count = 8"));assert(!js.includes(": number"));fs.writeFileSync("generated.cjs", js);console.log(require("./generated.cjs").count);
// File: input.ts (omit this label)export const count: number = 7;
// Run: node example.cjs// Expected stdout: 8