AST 的每个节点都有一个 type
字段,用来标识它的语法类型。
程序结构节点
type 说明 示例 Program
整个程序的根节点 整体代码结构 BlockStatement
大括号代码块 {}
if、function、for 等的主体 ExpressionStatement
表达式语句(如 a + b;
) EmptyStatement
分号 ;
空语句
变量与赋值
type 说明 示例 VariableDeclaration
变量声明(var/let/const) var a = 1;
VariableDeclarator
声明项 a = 1
AssignmentExpression
赋值表达式 a = b + 1
Identifier
标识符(变量名) a
Literal
字面量(数/字符串等) "abc"
, 123
, true
函数定义与调用
type 说明 示例 FunctionDeclaration
声明式函数 function fn() {}
FunctionExpression
表达式形式的函数 var f = function() {}
ArrowFunctionExpression
箭头函数 ()=>{}
CallExpression
函数调用 fn(arg1, arg2)
ReturnStatement
返回语句 return 123
运算表达式
type 说明 示例 BinaryExpression
二元运算符 a + b
, x * y
LogicalExpression
逻辑运算符(&&、 UnaryExpression
一元运算(+a、-b、!x) !isLogin
UpdateExpression
自增自减 ++ -- i++
, --x
AssignmentExpression
赋值表达式 a = b + 1
ConditionalExpression
三元表达式 a ? b : c
对象与数组相关
type 说明 示例 ObjectExpression
对象字面量 {a:1, b:2}
Property
对象的属性 a:1
ArrayExpression
数组字面量 [1, 2, 3]
MemberExpression
属性访问 obj.prop 或 obj["a"] obj.a
, arr[0]
流程控制语句
type 说明 示例 IfStatement
if 语句 if (x) {}
SwitchStatement
switch 语句 switch(x){}
SwitchCase
switch 的 case 分支 case 1:
WhileStatement
while 循环 while (true) {}
DoWhileStatement
do...while 循环 do {} while (true)
ForStatement
for 循环 for (let i=0;i<10;i++)
BreakStatement
break break;
ContinueStatement
continue continue;
全局对象 / 关键字
type 说明 示例 ThisExpression
this
this.a
NewExpression
new
表达式new Date()
SequenceExpression
多个表达式用逗号隔开 a = 1, b = 2
ThrowStatement
throw
抛出错误throw new Error("msg")
TryStatement
try-catch-finally 结构 try { ... } catch (e) {}
特殊用途(混淆常用)
type 说明 示例 Eval
(间接通过 CallExpression)用 eval 执行的内容会被解析为表达式树 eval("var a = 1")
Function
+ Function()
动态生成函数 new Function("a", "b", "return a + b")
TemplateLiteral
模板字符串(含 ${}
) `hello ${name}`
TaggedTemplateExpression
标签模板(如 crypto 模板 tag 加密) tag
hello`
如何查看 type?
可以直接用 Babel 插件、AST Explorer 来查看节点类型:
工具推荐:
traverse(ast, {enter(path) {console.log(path.node.type); // 输出每个节点的类型}
});