Last active
May 15, 2018 14:39
-
-
Save cevek/f7535e0818b6f0e9165d5b59ecf0410c to your computer and use it in GitHub Desktop.
Replace transformer example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function foo() {} | |
var a = foo(); | |
var b = foo(); | |
function bar() { | |
const foo = 1; | |
return foo + 2; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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