I am currently generating a custom AST from a new language specification I have designed. This custom AST contains different nodes that I have designed with all the information I need in order to now generate JavaScript code. For example:
Say I have a customExpressionNode which I wish to translate into a JavaScript function which contains a couple of if conditions.
I am currently looking into libraries like Babylon and Esprima for generating a new Javascript AST from my Custom AST, but from what I've seen there is quite a lot of complexity in the AST that these libraries use. I would also like to avoid printing js code into a few files and then parsing and compiling them, so my question is:
Is there a better way of generating programmatically a JavaScript compliant AST that I can use to generate JavaScript code?
Something like this? https://github.com/estools/escodegen
A simple example: the program
escodegen.generate({
type: 'BinaryExpression',
operator: '+',
left: { type: 'Literal', value: 40 },
right: { type: 'Literal', value: 2 }
})
produces the string '40 + 2'
.
npm install --save-dev @babel/generator
const { default: generate } = require("@babel/generator");
Identifier(path) {
console.log(generate(path.node).code); // code string
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With