AST 的处理
某些情况下,我们需要分析 JS 的语法结构,这个时候,就需要得到 AST,然后遍历语法树,得到我们想要的节点的内容
通常会选择 babel 作为我们的语法解析工具
得到 AST
安装 @babel/core 即可,调用其中的 parse 方法对代码进行解析,得到了抽象语法树 AST
import babel from '@babel/core'
const code = `
function add(a, b) {
return a + b;
}
const result = add(1, 2);
`
const ast = babel.parse(code)
console.log(ast.program.body)
/*
[
Node {
type: 'FunctionDeclaration',
start: 1,
end: 43,
loc: SourceLocation {
start: [Position],
end: [Position],
filename: undefined,
identifierName: undefined
},
id: Node {
type: 'Identifier',
start: 10,
end: 13,
loc: [SourceLocation],
name: 'add'
},
generator: false,
async: false,
params: [ [Node], [Node] ],
body: Node {
type: 'BlockStatement',
start: 20,
end: 43,
loc: [SourceLocation],
body: [Array],
directives: []
}
},
Node {
type: 'VariableDeclaration',
start: 49,
end: 74,
loc: SourceLocation {
start: [Position],
end: [Position],
filename: undefined,
identifierName: undefined
},
declarations: [ [Node] ],
kind: 'const'
}
]
*/我们打印了 body 的内容,是一个数组,分别是函数声明和变量声明,正是我们代码的内容,我们可以顺着节点,访问到节点详细的信息