File size: 1,199 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Babel plugin that wraps `warn` calls with development check to be
 * completely stripped from the production bundle.
 *
 * In the development bundle, warnings get wrapped with their condition
 * and their condition becomes false to trigger them without evaluating twice.
 *
 * Input:
 *
 * ```
 * warning(condition, message);
 * ```
 *
 * Output:
 *
 * ```
 * if (__DEV__) {
 *   warning(condition, message);
 * }
 * ```
 */

function wrapWarningWithDevCheck(babel) {
  const t = babel.types;

  const DEV_EXPRESSION = t.identifier('__DEV__');
  const SEEN_SYMBOL = Symbol('expression.seen');
  const IDENTIFIER_NAME = 'warn';

  return {
    visitor: {
      CallExpression: {
        exit(path) {
          const node = path.node;

          if (node[SEEN_SYMBOL]) {
            return;
          }

          if (path.get('callee').isIdentifier({ name: IDENTIFIER_NAME })) {
            node[SEEN_SYMBOL] = true;

            path.replaceWith(
              t.ifStatement(
                DEV_EXPRESSION,
                t.blockStatement([t.expressionStatement(node)])
              )
            );
          }
        },
      },
    },
  };
}

module.exports = wrapWarningWithDevCheck;