/
index.js
71 lines (62 loc) · 1.92 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
62
63
64
65
66
67
68
69
70
71
"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) && !path.parentPath.isMemberExpression()) {
if (path.parentPath.isAssignmentExpression() && path.parentKey === "left") {
path.parentPath.get("right").replaceWith(createNoop());
} else {
path.replaceWith(createNoop());
}
}
}
}
}
};
function isGlobalConsoleId(id) {
const name = "console";
return id.isIdentifier({ name })
&& !id.scope.getBinding(name)
&& id.scope.hasGlobal(name);
}
function isConsole(memberExpr) {
const object = memberExpr.get("object");
if (isGlobalConsoleId(object)) return true;
const property = memberExpr.get("property");
return isGlobalConsoleId(object.get("object"))
&& (
property.isIdentifier({ name: "call" })
|| property.isIdentifier({ name: "apply" })
);
}
function isConsoleBind(memberExpr) {
const object = memberExpr.get("object");
return object.isMemberExpression()
&& isGlobalConsoleId(object.get("object"))
&& memberExpr.get("property").isIdentifier({ name: "bind" });
}
function createNoop() {
return t.functionExpression(null, [], t.blockStatement([]));
}
function createVoid0() {
return t.unaryExpression("void", t.numericLiteral(0));
}
};