是一个JS parser Uglify 用到了它
var esprima = require('esprima');
var program = 'const answer = 42';
esprima.tokenize(program)
//we get this
[ { type: 'Keyword', value: 'const' },
{ type: 'Identifier', value: 'answer' },
{ type: 'Punctuator', value: '=' },
{ type: 'Numeric', value: '42' } ]
parse 将得到抽象语法树AST
esprima.parse(program)
因为只有 const answer = 42 这么一句
所以语法树是一个长度为1的数组
这句话是一个变量声明 variable declaration
转为 AST 得到下面信息
如果有两句话呢 比如这样
program = 'var a = 1; if(a == 1){console.log(1)}else{console.log(\'not 1\')}';
ast = esprima.parse(program);
第一句是变量声明 第二句是if条件判断语句
条件判断语句又包括三个部分 判断条件和两个 语句块
在一个语句块中又只有一句话(body:array[1])
这句话里
又只有一个表达式 (array[0]是ExpressionStatement)
这个表达式console.log(1)的参数是一个数字1
expression 再展开
//then we got
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "a"
},
"init": {
"type": "Literal",
"value": 1,
"raw": "1"
}
}
],
"kind": "var"
},
{
"type": "IfStatement",
"test": {
"type": "BinaryExpression",
"operator": "==",
"left": {
"type": "Identifier",
"name": "a"
},
"right": {
"type": "Literal",
"value": 1,
"raw": "1"
}
},
"consequent": {
"type": "BlockStatement",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "CallExpression",
"callee": {
"type": "MemberExpression",
"computed": false,
"object": {
"type": "Identifier",
"name": "console"
},
"property": {
"type": "Identifier",
"name": "log"
}
},
"arguments": [
{
"type": "Literal",
"value": 1,
"raw": "1"
}
]
}
}
]
},
"alternate": {
"type": "BlockStatement",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "CallExpression",
"callee": {
"type": "MemberExpression",
"computed": false,
"object": {
"type": "Identifier",
"name": "console"
},
"property": {
"type": "Identifier",
"name": "log"
}
},
"arguments": [
{
"type": "Literal",
"value": "not 1",
"raw": "'not 1'"
}
]
}
}
]
}
}
],
"sourceType": "script"
}