auto-importer.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. const MODULES = [
  9. // Local Promise implementation.
  10. 'Promise',
  11. ];
  12. /**
  13. * Automatically imports a module if its identifier is in the AST.
  14. */
  15. module.exports = function autoImporter(babel) {
  16. const t = babel.types;
  17. function isAppropriateModule(name, scope, state) {
  18. const autoImported = state.autoImported;
  19. return MODULES.indexOf(name) !== -1
  20. && !autoImported.hasOwnProperty(name)
  21. && !scope.hasBinding(name, /*skip globals*/true);
  22. }
  23. return {
  24. pre: function() {
  25. // Cache per file to avoid calling `scope.hasBinding` several
  26. // times for the same module, which has already been auto-imported.
  27. this.autoImported = {};
  28. },
  29. visitor: {
  30. ReferencedIdentifier: function(path) {
  31. const node = path.node;
  32. const scope = path.scope;
  33. if (!isAppropriateModule(node.name, scope, this)) {
  34. return;
  35. }
  36. scope.getProgramParent().push({
  37. id: t.identifier(node.name),
  38. init: t.callExpression(
  39. t.identifier('require'),
  40. [t.stringLiteral(node.name)]
  41. ),
  42. });
  43. this.autoImported[node.name] = true;
  44. },
  45. },
  46. };
  47. };