escodegen.generate throws Error: Unknown node type: undefined

1.1k views Asked by At

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.

1

There are 1 answers

3
fonkap On BEST ANSWER

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