@samitouri / QOS-React-2 / commits / 02f1626725

Better invariant / warning replacement

Paul O’Shannessy committed May 21, 2015 at 19:08 UTC 02f16267257ed241a9f4febe1aaf457b80f1d79d
2 files changed +65 -13
package.json
+1 -1
@@ -67,7 +67,7 @@
67 },
68 "preferGlobal": true,
69 "commonerConfig": {
70 - "version": 6
70 + "version": 7
71 },
72 "scripts": {
73 "test": "jest",
vendor/constants.js
+64 -12
@@ -37,21 +37,73 @@ module.exports = function(babel) {
37 CallExpression: {
38 exit: function(node, parent) {
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 + ])
84 );
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(
101 DEV_EXPRESSION,
53 - node,
54 - t.literal(null)
102 + t.blockStatement([
103 + t.expressionStatement(
104 + node
105 + )
106 + ])
107 );
108 }
109 }