babel是个js编译器,写babel插件其实就是操作ast。
我们日常项目中使用ast的场景很多,比如eslint, codemods, css parsers, css in js等等,不同的工具的ast解析规则可能稍有区别,这里以babel的规范为主。
ast介绍
ast的定义如下
An abstract syntax tree is a tree representation of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.
ast的处理包括三个步骤, parse, transform, generate,我们关注点在前两步,具体要操作的是第二步。
parse
将源码解析成ast分为两步,词法分析和语法分析,以 const a = 5 + 3;
为例。
词法分析是将源码字符串拆分成一个个token,我们这里把token简化为
interface Token {
type: string,
value: string
}
我们例子里的结果就是
语法分析就是将这些token组合成ast
大概如下
{
"type": "VariableDeclaration",
"declarations": [{
"type": "VariableDeclarator",