Reputation: 6888
In the below code, is it possible to get the whole string representation of the AST node which would in this case return the window.alert('asdf')
?
const ast = parse("window.alert('asdf')")
let preloadCode = ""
traverse(ast, {
CallExpression: function(path) {
// path.node.toString() ??
},
})
Upvotes: 3
Views: 4216
Reputation: 13560
If writing a plugin using babel >= 7.22.5 you can do this:
export default function () {
return {
visitor: {
CallExpression(path, state) {
const { node } = path
const { code } = state.file
console.log(code.slice(node.start, node.end))
}
}
}
}
Upvotes: 0
Reputation: 2701
@babel/traverse, version 7.18.3
Just use path.toString()
:
const ast = parse("window.alert('asdf')")
traverse(ast, {
CallExpression: function(path) {
console.log(path.toString());
},
})
Found it here
Upvotes: 2
Reputation: 160
There is a method https://npmdoc.github.io/node-npmdoc-babel-core/build/apidoc.html#apidoc.element.babel-core.traverse.NodePath.prototype.getSource
const ast = parse("window.alert('asdf')")
let preloadCode = ""
traverse(ast, {
CallExpression: function(path) {
// path.node.toString()
path.getSource()
},
})
Upvotes: 1
Reputation: 589
Each AST node returned by @babel/parser
has a start
and end
properties pointing to it's location in the source code. You can use those to slice the source for the original string.
const { parse } = require('@babel/parser');
const source = '1 + 2 + 3';
const ast = parse(source);
const node = ast.program.body[0].expression.left;
console.log(source.slice(node.start, node.end)); // → '1 + 2'
Upvotes: 6
Reputation: 589
You are probably looking for https://babeljs.io/docs/en/babel-generator
Try this:
const { default: generate } = require('@babel/generator');
module.exports = () => ({
visitor: {
Identifier: (path, state) => {
console.log(generate(path.parent));
},
},
});
Upvotes: 3