index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = hoistVariables;
  6. var _t = require("@babel/types");
  7. const {
  8. assignmentExpression,
  9. expressionStatement,
  10. identifier
  11. } = _t;
  12. const visitor = {
  13. Scope(path, state) {
  14. if (state.kind === "let") path.skip();
  15. },
  16. FunctionParent(path) {
  17. path.skip();
  18. },
  19. VariableDeclaration(path, state) {
  20. if (state.kind && path.node.kind !== state.kind) return;
  21. const nodes = [];
  22. const declarations = path.get("declarations");
  23. let firstId;
  24. for (const declar of declarations) {
  25. firstId = declar.node.id;
  26. if (declar.node.init) {
  27. nodes.push(expressionStatement(assignmentExpression("=", declar.node.id, declar.node.init)));
  28. }
  29. for (const name of Object.keys(declar.getBindingIdentifiers())) {
  30. state.emit(identifier(name), name, declar.node.init !== null);
  31. }
  32. }
  33. if (path.parentPath.isFor({
  34. left: path.node
  35. })) {
  36. path.replaceWith(firstId);
  37. } else {
  38. path.replaceWithMultiple(nodes);
  39. }
  40. }
  41. };
  42. function hoistVariables(path, emit, kind = "var") {
  43. path.traverse(visitor, {
  44. kind,
  45. emit
  46. });
  47. }
  48. //# sourceMappingURL=index.js.map