-
Notifications
You must be signed in to change notification settings - Fork 1
/
babel-plugin-demo
77 lines (70 loc) · 2 KB
/
babel-plugin-demo
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// babel plugin
export default function (babel) {
const { types: t } = babel;
return {
name: 'ast-transform', // not required
visitor: {
Identifier(path) {
// path.node.name = path.node.name.split('').reverse().join('');
//const parentPath = path.findParent((path) => path.isFunctionDeclaration());
//console.log('ttt', parentPath);
//if (parentPath) {
// const param = parentPath.node.params.find((p) => p.name === path.node.name && t.isIdentifier(p));
// if (param) {
// param.name = 'a';
// }
//}
},
ArrayExpression(path) {
path.node.elements.push(t.numberLiteral(10));
},
NumericLiteral(path) {
if (
path.node.value === 2 &&
path.findParent((path) => path.isIfStatement())
) {
path.node.value *= 10;
}
},
FunctionDeclaration(path) {
const paramsNames = path.node.params.map((item) => {
if (t.isIdentifier(item)) {
return item.name;
}
if (t.isAssignmentPattern) {
return item.left.name;
}
});
const pPrefix = 'a';
path.stop();
path.traverse({
Identifier(path) {
console.log('f_i', path.node);
paramsNames.forEach((p, index) => {
if (path.node.name === p) {
path.node.name = `${pPrefix}${index}`;
path.node.end -= 1;
}
});
},
});
},
ArrowFunctionExpression(path) {
const { node } = path;
console.log('arrow', path);
const blockStatement = t.isBlockStatement(node.body)
? node.body
: t.blockStatement([t.returnStatement(node.body)]);
path.replaceWith(
t.functionExpression(
null,
node.params,
blockStatement,
node.generator,
node.async
)
);
},
},
};
}