index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = splitExportDeclaration;
  6. var _t = require("@babel/types");
  7. const {
  8. cloneNode,
  9. exportNamedDeclaration,
  10. exportSpecifier,
  11. identifier,
  12. variableDeclaration,
  13. variableDeclarator
  14. } = _t;
  15. function splitExportDeclaration(exportDeclaration) {
  16. if (!exportDeclaration.isExportDeclaration()) {
  17. throw new Error("Only export declarations can be split.");
  18. }
  19. const isDefault = exportDeclaration.isExportDefaultDeclaration();
  20. const declaration = exportDeclaration.get("declaration");
  21. const isClassDeclaration = declaration.isClassDeclaration();
  22. if (isDefault) {
  23. const standaloneDeclaration = declaration.isFunctionDeclaration() || isClassDeclaration;
  24. const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
  25. let id = declaration.node.id;
  26. let needBindingRegistration = false;
  27. if (!id) {
  28. needBindingRegistration = true;
  29. id = scope.generateUidIdentifier("default");
  30. if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) {
  31. declaration.node.id = cloneNode(id);
  32. }
  33. }
  34. const updatedDeclaration = standaloneDeclaration ? declaration : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
  35. const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
  36. exportDeclaration.insertAfter(updatedExportDeclaration);
  37. exportDeclaration.replaceWith(updatedDeclaration);
  38. if (needBindingRegistration) {
  39. scope.registerDeclaration(exportDeclaration);
  40. }
  41. return exportDeclaration;
  42. }
  43. if (exportDeclaration.get("specifiers").length > 0) {
  44. throw new Error("It doesn't make sense to split exported specifiers.");
  45. }
  46. const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
  47. const specifiers = Object.keys(bindingIdentifiers).map(name => {
  48. return exportSpecifier(identifier(name), identifier(name));
  49. });
  50. const aliasDeclar = exportNamedDeclaration(null, specifiers);
  51. exportDeclaration.insertAfter(aliasDeclar);
  52. exportDeclaration.replaceWith(declaration.node);
  53. return exportDeclaration;
  54. }