Extend Astring with a custom generator
mainYou can extend Astring by providing a custom generator in the options object. A generator is an object mapping node names to functions. Each function receives two arguments:
node: The AST node to generate code from.state: An object exposing awrite(string)method to append generated code.
To inherit existing behavior, use Object.assign({}, astring.GENERATOR, { ... }) to create your custom generator.
Example: Adding support for AwaitExpression
var customGenerator = Object.assign({}, astring.GENERATOR, {
AwaitExpression: function (node, state) {
state.write('await ')
var argument = node.argument
if (argument != null) {
this[argument.type](argument, state)
}
},
})
var ast = {
type: 'AwaitExpression',
argument: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'callable',
},
arguments: [],
},
}
var code = astring.generate(ast, {
generator: customGenerator,
})
console.log(code === 'await callable();\n' ? 'It works!' : 'Something went wrong!')// Make sure the astring module is imported and that `Object.assign` is defined
// Create a custom generator that inherits from Astring's base generator
var customGenerator = Object.assign({}, astring.GENERATOR, {
AwaitExpression: function (node, state) {
state.write('await ')
var argument = node.argument
if (argument != null) {
this[argument.type](argument, state)
}
},
})
// Obtain a custom AST somehow (note that this AST is not obtained from a valid code)
var ast = {
type: 'AwaitExpression',
argument: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'callable',
},
arguments: [],
},
}
// Format it
var code = astring.generate(ast, {
generator: customGenerator,
})
// Check it
console.log(
code === 'await callable();\n' ? 'It works!' : 'Something went wrong!',
)