-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabel.js
49 lines (47 loc) · 1.13 KB
/
babel.js
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
40
41
42
43
44
45
46
47
48
49
const babel = require('@babel/core');
const trverse = require('@babel/traverse').default;
const code = `a["b"].x.m ? c.d.e.f: ''`;
var ast = babel.parse(code);
var l = []
trverse(ast, {
Identifier(p) {
const node = p.node;
// console.log(node.name)
},
MemberExpression(p) {
// var obj = {
// name: '',
// property: ''
// }
const node = p.node;
propertyCollection(node, l)
}
});
console.log(l)
function propertyCollection(node, l, obj = {
name: '',
property: ''
}) {
const object = node.object;
const property = node.property;
if (object) {
obj.name = object.name;
let computed = node.computed;
let isIdentifier = property.type === 'Identifier';
let concatProperty = '';
if (computed) {
console.log(property)
concatProperty = isIdentifier ? `[${property.name}]` : `[${property.extra.raw}]`;
} else {
concatProperty = `.${property.name}`;
}
obj.property = concatProperty + obj.property;
if (object.object) {
propertyCollection(object, l, obj);
} else {
if (!l.find(o => o.name === obj.name)) {
l.push(obj);
}
}
}
}