Skip to content

Instantly share code, notes, and snippets.

@cevek
Last active May 15, 2018 14:39
Show Gist options
  • Save cevek/f7535e0818b6f0e9165d5b59ecf0410c to your computer and use it in GitHub Desktop.
Save cevek/f7535e0818b6f0e9165d5b59ecf0410c to your computer and use it in GitHub Desktop.
Replace transformer example
function foo() {}
var a = foo();
var b = foo();
function bar() {
const foo = 1;
return foo + 2;
}
import * as ts from 'typescript';
const replace = {
from: 'foo',
to: 'xxx',
};
export default function(program: ts.Program) {
const checker = program.getTypeChecker();
return (ctx: ts.TransformationContext) => sourceFile => {
const fromSymbol = checker
.getSymbolsInScope(sourceFile, ts.SymbolFlags.Function)
.find(symbol => symbol.escapedName === replace.from);
if (!fromSymbol) return sourceFile;
function visitor(node: ts.Node): ts.Node {
if (ts.isFunctionDeclaration(node)) {
const symbol = checker.getSymbolAtLocation(node.name);
if (symbol === fromSymbol) {
node = ts.updateFunctionDeclaration(
node,
node.decorators,
node.modifiers,
node.asteriskToken,
ts.createIdentifier(replace.to),
node.typeParameters,
node.parameters,
node.type,
node.body
);
}
}
if (ts.isCallExpression(node)) {
const symbol = checker.getSymbolAtLocation(node.expression);
if (symbol === fromSymbol) {
node = ts.updateCall(node, ts.createIdentifier(replace.to), node.typeArguments, node.arguments);
}
}
return ts.visitEachChild(node, visitor, ctx);
}
return ts.visitEachChild(sourceFile, visitor, ctx);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment