@@ -37,21 +37,73 @@ module.exports = function(babel) {
37
37
CallExpression : {
38
38
exit : function ( node , parent ) {
39
39
if ( this . get ( 'callee' ) . isIdentifier ( { name : 'invariant' } ) ) {
40
- // Truncate the arguments of invariant(condition, ...)
41
- // statements to just the condition based on NODE_ENV
42
- // (dead code removal will remove the extra bytes).
43
- return t . conditionalExpression (
44
- DEV_EXPRESSION ,
45
- node ,
46
- t . callExpression ( node . callee , [ node . arguments [ 0 ] ] )
40
+ // Turns this code:
41
+ //
42
+ // invariant(condition, argument, argument);
43
+ //
44
+ // into this:
45
+ //
46
+ // if (!condition) {
47
+ // if ("production" !== process.env.NODE_ENV) {
48
+ // invariant(false, argument, argument);
49
+ // } else {
50
+ // invariant(false);
51
+ // }
52
+ // }
53
+ //
54
+ // Specifically this does 2 things:
55
+ // 1. Checks the condition first, preventing an extra function call.
56
+ // 2. Adds an environment check so that verbose error messages aren't
57
+ // shipped to production.
58
+ // The generated code is longer than the original code but will dead
59
+ // code removal in a minifier will strip that out.
60
+ var condition = node . arguments [ 0 ] ;
61
+ return t . ifStatement (
62
+ t . unaryExpression ( '!' , condition ) ,
63
+ t . blockStatement ( [
64
+ t . ifStatement (
65
+ DEV_EXPRESSION ,
66
+ t . blockStatement ( [
67
+ t . expressionStatement (
68
+ t . callExpression (
69
+ node . callee ,
70
+ [ t . literal ( false ) ] . concat ( node . arguments . slice ( 1 ) )
71
+ )
72
+ )
73
+ ] ) ,
74
+ t . blockStatement ( [
75
+ t . expressionStatement (
76
+ t . callExpression (
77
+ node . callee ,
78
+ [ t . literal ( false ) ]
79
+ )
80
+ )
81
+ ] )
82
+ )
83
+ ] )
47
84
) ;
48
85
} else if ( this . get ( 'callee' ) . isIdentifier ( { name : 'warning' } ) ) {
49
- // Eliminate warning(condition, ...) statements based on NODE_ENV
50
- // (dead code removal will remove the extra bytes).
51
- return t . conditionalExpression (
86
+ // Turns this code:
87
+ //
88
+ // warning(condition, argument, argument);
89
+ //
90
+ // into this:
91
+ //
92
+ // if ("production" !== process.env.NODE_ENV) {
93
+ // warning(condition, argument, argument);
94
+ // }
95
+ //
96
+ // The goal is to strip out warning calls entirely in production. We
97
+ // don't need the same optimizations for conditions that we use for
98
+ // invariant because we don't care about an extra call in __DEV__
99
+
100
+ return t . ifStatement (
52
101
DEV_EXPRESSION ,
53
- node ,
54
- t . literal ( null )
102
+ t . blockStatement ( [
103
+ t . expressionStatement (
104
+ node
105
+ )
106
+ ] )
55
107
) ;
56
108
}
57
109
}
0 commit comments