object-assign.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 autoImporter(babel) {
  9. const t = babel.types;
  10. function getAssignIdent(path, file, state) {
  11. if (!state.id) {
  12. state.id = path.scope.generateUidIdentifier('assign');
  13. path.scope.getProgramParent().push({
  14. id: state.id,
  15. init: t.callExpression(
  16. t.identifier('require'),
  17. [t.stringLiteral('object-assign')]
  18. ),
  19. });
  20. }
  21. return state.id;
  22. }
  23. return {
  24. pre: function() {
  25. // map from module to generated identifier
  26. this.id = null;
  27. },
  28. visitor: {
  29. CallExpression: function(path, file) {
  30. if (path.get('callee').matchesPattern('Object.assign')) {
  31. // generate identifier and require if it hasn't been already
  32. var id = getAssignIdent(path, file, this);
  33. path.node.callee = id;
  34. }
  35. },
  36. MemberExpression: function(path, file) {
  37. if (path.matchesPattern('Object.assign')) {
  38. var id = getAssignIdent(path, file, this);
  39. path.replaceWith(id);
  40. }
  41. },
  42. },
  43. };
  44. };