Guest User

Untitled

a guest
Jun 24th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import * as ts from 'typescript';
  2.  
  3. let options = {
  4. stripInternal: true,
  5. target: ts.ScriptTarget.ES5,
  6. experimentalDecorators: true,
  7. listEmittedFiles: true
  8. };
  9.  
  10. function transform(ctx: ts.TransformationContext): ts.Transformer<ts.SourceFile> {
  11. return (rootNode): ts.SourceFile => {
  12. const visitChildren: ts.Visitor = (node: ts.Node): ts.VisitResult<ts.Node> => {
  13. console.log('Node kind=', ts.SyntaxKind[node.kind]);
  14. node = ts.visitEachChild(node, visitChildren, ctx);
  15. if (ts.isMethodDeclaration(node)) {
  16. let methodDecl: ts.MethodDeclaration = <ts.MethodDeclaration> node;
  17. if (methodDecl && methodDecl.name) {
  18. let name = <ts.Identifier> methodDecl.name;
  19. let text = name.text;
  20. if (text === 'getFoo') {
  21. let newName: ts.Identifier = ts.createIdentifier('getFooBar');
  22. return ts.updateMethod(
  23. methodDecl,
  24. methodDecl.decorators,
  25. methodDecl.modifiers,
  26. methodDecl.asteriskToken,
  27. newName,
  28. methodDecl.questionToken,
  29. methodDecl.typeParameters,
  30. methodDecl.parameters,
  31. methodDecl.type,
  32. methodDecl.body
  33. );
  34. }
  35. }
  36. }
  37. return node;
  38. }
  39. return ts.visitNode(rootNode, visitChildren);
  40. }
  41. }
  42.  
  43.  
  44. const filePath = '/Users/keithstrickland/RedPill/NPM/ts-compiler-experiment/src/data/sample.ts';
  45. const newFilePath = '/Users/keithstrickland/RedPill/NPM/ts-compiler-experiment/src/data/sample_transformed.ts';
  46. const program = ts.createProgram(
  47. [filePath],
  48. options
  49. );
  50. const sourceFile = program.getSourceFile(filePath);
  51. const result: ts.TransformationResult<ts.SourceFile> = ts.transform(sourceFile, [transform], options);
  52. const transformedSourceFile: ts.SourceFile = result.transformed[0];
  53. const newSource: ts.SourceFile = ts.createSourceFile(
  54. newFilePath,
  55. transformedSourceFile.getText(),
  56. ts.ScriptTarget.ES5,
  57. false,
  58. ts.ScriptKind.TS);
  59. const printer: ts.Printer = ts.createPrinter({newLine: ts.NewLineKind.LineFeed});
  60. printer.printFile(newSource);
Add Comment
Please, Sign In to add comment