Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as ts from 'typescript';
- let options = {
- stripInternal: true,
- target: ts.ScriptTarget.ES5,
- experimentalDecorators: true,
- listEmittedFiles: true
- };
- function transform(ctx: ts.TransformationContext): ts.Transformer<ts.SourceFile> {
- return (rootNode): ts.SourceFile => {
- const visitChildren: ts.Visitor = (node: ts.Node): ts.VisitResult<ts.Node> => {
- console.log('Node kind=', ts.SyntaxKind[node.kind]);
- node = ts.visitEachChild(node, visitChildren, ctx);
- if (ts.isMethodDeclaration(node)) {
- let methodDecl: ts.MethodDeclaration = <ts.MethodDeclaration> node;
- if (methodDecl && methodDecl.name) {
- let name = <ts.Identifier> methodDecl.name;
- let text = name.text;
- if (text === 'getFoo') {
- let newName: ts.Identifier = ts.createIdentifier('getFooBar');
- return ts.updateMethod(
- methodDecl,
- methodDecl.decorators,
- methodDecl.modifiers,
- methodDecl.asteriskToken,
- newName,
- methodDecl.questionToken,
- methodDecl.typeParameters,
- methodDecl.parameters,
- methodDecl.type,
- methodDecl.body
- );
- }
- }
- }
- return node;
- }
- return ts.visitNode(rootNode, visitChildren);
- }
- }
- const filePath = '/Users/keithstrickland/RedPill/NPM/ts-compiler-experiment/src/data/sample.ts';
- const newFilePath = '/Users/keithstrickland/RedPill/NPM/ts-compiler-experiment/src/data/sample_transformed.ts';
- const program = ts.createProgram(
- [filePath],
- options
- );
- const sourceFile = program.getSourceFile(filePath);
- const result: ts.TransformationResult<ts.SourceFile> = ts.transform(sourceFile, [transform], options);
- const transformedSourceFile: ts.SourceFile = result.transformed[0];
- const newSource: ts.SourceFile = ts.createSourceFile(
- newFilePath,
- transformedSourceFile.getText(),
- ts.ScriptTarget.ES5,
- false,
- ts.ScriptKind.TS);
- const printer: ts.Printer = ts.createPrinter({newLine: ts.NewLineKind.LineFeed});
- printer.printFile(newSource);
Add Comment
Please, Sign In to add comment