esprima401 astbodyforEachnode = nodebody 如何获取源码内容
获取源码内容需要借助于源代码字符串。可以使用 node.range 属性获取节点所在的字符位置,然后从源代码字符串中截取相应位置的子字符串即可。
示例代码:
const sourceCode = 'function foo() { console.log("Hello, world!"); }';
const ast = esprima.parseScript(sourceCode);
ast.body.forEach(node => {
const { start, end } = node.range;
const code = sourceCode.substring(start, end);
console.log(code);
});
输出:
function foo() { console.log("Hello, world!"); }
原文地址: https://www.cveoy.top/t/topic/9XZ 著作权归作者所有。请勿转载和采集!