-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplug.js
More file actions
39 lines (38 loc) · 1.22 KB
/
plug.js
File metadata and controls
39 lines (38 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const t = require('babel-types');
const visitor = {
BinaryExpression(path) {
const node = path.node;
let result;
// 两边都是数字数字
if (t.isNumericLiteral(node.left) && t.isNumericLiteral(node.right)) {
switch (node.operator) {
case "+":
result = node.left.value + node.right.value;
break;
case "-":
result = node.left.value - node.right.value;
break;
case "*":
result = node.left.value * node.right.value;
break;
case "/":
result = node.left.value / node.right.value;
break;
default:
break;
}
}
if (result !== void 0) {
// 将节点表达式替换成result字面量
path.replaceWith(t.numericLiteral(result));
let parentPath = path.parentPath;
// 存在父节点 && 向上遍历父级节点
parentPath && visitor.BinaryExpression.call(this, parentPath);
}
}
};
module.exports = function (babel) {
return {
visitor
};
};