dev-declaration.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. module.exports = function(babel) {
  9. const t = babel.types;
  10. // We can't construct an identifier with a type annotation all in 1 fell swoop
  11. // so we have to create & mutate, then pass along.
  12. const DEV_IDENTIFIER = t.identifier('__DEV__');
  13. DEV_IDENTIFIER.typeAnnotation = t.typeAnnotation(t.booleanTypeAnnotation());
  14. const DEV_DECLARATION = t.declareVariable(
  15. DEV_IDENTIFIER
  16. );
  17. return {
  18. pre() {
  19. this.usesDEV = false;
  20. },
  21. visitor: {
  22. Identifier: {
  23. enter(path, file) {
  24. this.usesDEV = this.usesDEV || path.isIdentifier({name: '__DEV__'});
  25. },
  26. },
  27. Program: {
  28. exit(path, file) {
  29. if (!this.usesDEV) {
  30. return;
  31. }
  32. // Add the declaration at the front of the body if we've used __DEV__.
  33. path.node.body.unshift(DEV_DECLARATION);
  34. },
  35. },
  36. },
  37. };
  38. };