/
index.js
61 lines (53 loc) · 1.63 KB
/
index.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
50
51
52
53
54
55
56
57
58
59
60
61
"use strict";
module.exports = function({ types: t }) {
return {
name: "transform-remove-console",
visitor: {
CallExpression(path) {
const callee = path.get("callee");
if (!callee.isMemberExpression()) return;
if (isConsole(callee)) {
// console.log()
if (path.parentPath.isExpressionStatement()) {
path.remove();
} else {
path.replaceWith(createVoid0());
}
} else if (isConsoleBind(callee)) {
// console.log.bind()
path.replaceWith(createNoop());
}
},
MemberExpression: {
exit(path) {
if (!isConsole(path)) return;
if (!path.parentPath.isMemberExpression()) {
path.replaceWith(createNoop());
}
}
}
},
};
function isConsole(memberExpr) {
const object = memberExpr.get("object");
if (object.isIdentifier({ name: "console" })) return true;
const property = memberExpr.get("property");
return object.get("object").isIdentifier({ name: "console" })
&& (
property.isIdentifier({ name: "call" })
|| property.isIdentifier({ name: "apply" })
);
}
function isConsoleBind(memberExpr) {
const object = memberExpr.get("object");
return object.isMemberExpression()
&& object.get("object").isIdentifier({ name: "console" })
&& memberExpr.get("property").isIdentifier({ name: "bind" });
}
function createNoop() {
return t.functionExpression(null, [], t.blockStatement([]));
}
function createVoid0() {
return t.unaryExpression("void", t.numericLiteral(0));
}
};