-
Notifications
You must be signed in to change notification settings - Fork 30
/
wrap-validate-with-env-check.js
56 lines (50 loc) · 1.82 KB
/
wrap-validate-with-env-check.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
module.exports = function(babel, options) {
"use strict";
const t = babel.types;
const NODE_ENV = t.memberExpression(t.memberExpression(t.identifier("process"), t.identifier("env")), t.identifier("NODE_ENV"));
const PRODUCTION_EXPRESSION = t.binaryExpression("!==", NODE_ENV, t.stringLiteral("production"));
const SEEN_SYMBOL = Symbol('expression.seen');
return {
visitor: {
CallExpression: {
exit: function(path) {
const node = path.node;
// Ignore if it's already been processed
if (node[SEEN_SYMBOL]) {
return;
}
if (
path.get('callee').isIdentifier({name: 'validate'}) ||
path.get('callee').isIdentifier({name: 'validateType'}) ||
path.get('callee').isIdentifier({name: 'validateTypePath'}) ||
path.get('callee').isIdentifier({name: 'validateTypeString'}) ||
path.get('callee').isIdentifier({name: 'validateTypeFunction'}) ||
path.get('callee').isIdentifier({name: 'validateTypePlainObject'}) ||
path.get('callee').isIdentifier({name: 'validatePresence'})
) {
// Turns this code:
//
// validate(...);
//
// into this:
//
// if (process.env.NODE_ENV !== "production") {
// validate(...);
// }
//
// The goal is to strip out validation calls entirely in production.
node[SEEN_SYMBOL] = true;
path.replaceWith(
t.ifStatement(
PRODUCTION_EXPRESSION,
t.blockStatement([
t.expressionStatement(node),
])
)
);
}
},
},
},
};
};