0

The following is the code that I have written

`js
  var esprima = require('esprima');
  var escodegen = require('escodegen');
  var a = "var a = 2";
  var ast = esprima.tokenize(a);
  var output = escodegen.generate(ast);
  console.log(output);
`

I am able to tokenize the code string but I am getting error generating the code back. I went through multiple samples, Everywhere the same pattern is followed. I don't understand what I am doing wrong.

Vishal
  • 29
  • 7

1 Answers1

0

The function esprima.tokenize does not generate an AST, just an array of tokens. What you want to use is esprima.parse.

Try this:

  var esprima = require('esprima');
  var escodegen = require('escodegen');
  var a = "var a = 2";
  var ast = esprima.parse(a);
  var output = escodegen.generate(ast);
  console.log(output);

It will work

fonkap
  • 2,469
  • 1
  • 14
  • 30
  • Thanks but its working for a small code snippet. I am trying to parse a large code block of typescript for which it is throwing 'Unexpected token :' error. – Vishal Jan 14 '19 at 16:09
  • Well, that is a different problem. I think esprima cannot parse typescript, maybe you can find some information in this other question: https://stackoverflow.com/questions/39917907/typescript-ast-typescript – fonkap Jan 15 '19 at 21:50
  • Got it! Thanks for your help. – Vishal Jan 16 '19 at 19:14