admin管理员组文章数量:1287258
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() ??
},
})
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() ??
},
})
Share
Improve this question
asked Apr 20, 2020 at 15:17
SkaSka
6,90815 gold badges54 silver badges75 bronze badges
5 Answers
Reset to default 6Each 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'
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));
},
},
});
@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
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()
},
})
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))
}
}
}
}
本文标签: javascriptHow to get code as a string from Babel node during traverseStack Overflow
版权声明:本文标题:javascript - How to get code as a string from Babel node during traverse - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741261188a2367653.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论