AST学习-将a["length"]转变为a.length

将a[“length”]转变为a.length

目标

1
2
var a = 'hello world!';
var b = a['length'];

转化为

1
2
var a = 'hello world!';
var b = a.length;

分析

经AST-Tree比较获知差距在于 propertycomputed 这两个路径,替换掉就好了

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function member2identify(path){
const init = path.get('init');

if (!init.isMemberExpression()) return;

const member_node = init.node;
const member_property = init.get('property');

member_node.computed = false;
let value = member_node.property.value;
member_property.replaceWith(t.Identifier(value));
}

const vistor = {
VariableDeclarator:{
enter: [member2identify]
}
}

查看结果