代码转成语法树: astexplorer.net/
- esprima把源码转化为AST
- estraverse 遍历并更新AST
- escodegen将AST重新生成源码
// npm i esprima estraverse escodegen -S
1. ast:
{
"type": "Program",
"start": 0,
"end": 17,
"body": [
{
"type": "FunctionDeclaration",
"start": 0,
"end": 17,
"id": {
"type": "Identifier",
"start": 9,
"end": 12,
"name": "abc"
},
"expression": false,
"generator": false,
"async": false,
"params": [],
"body": {
"type": "BlockStatement",
"start": 15,
"end": 17,
"body": []
}
}
],
"sourceType": "module"
}
2.遍历
进入Program
进入FunctionDeclaration
进入Identifier
离开Identifier
进入BlockStatement
离开BlockStatement
离开FunctionDeclaration
离开Program