Together they can be used to inject instructions into the code, for example to log values.
Both can be used in either the browser or Node.
Parsing with Esprima
To load Esprima in the browsers we need to include the esprima.js file in the html code.
With Node run
npm install esprima --save and
Then use Esprima’s
parse method to generate the syntax tree:
It’s quite verbose, but we can now more easily iterate over the instructions.
To parse arguments to Esprima pass an options object as a second parameter:
The range option will add a character index to all parse tree elements:
Esprima has a tool that updates the syntax tree of entered code in real time
, which also shows some of the other options that are available, such as
loc to get line numbers and
include comments in the syntax tree.
Turning the syntax tree back into code using Escodegen
To get the browser version download the release
and look for the
escodegen.browser.js in the extracted folder.
On the server run
npm install escodegen --save and load the library with
var escodegen = require('escodegen').
Now to go full circle back to the original code call
escodgen.generate witht the parse tree as the first argument.
To inject code we modify the parse tree before passing it to Escodegen.
We can avoid having to deal with parse trees directly by passing the code we want to inject
esprima.parse before adding it to the parse tree:
Which gives us the original code wrapped by two function calls that we could use for example to log how long the function takes to execute: