index.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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() || exportDeclaration.isExportAllDeclaration()) {
  17. throw new Error("Only default and named export declarations can be split.");
  18. }
  19. if (exportDeclaration.isExportDefaultDeclaration()) {
  20. const declaration = exportDeclaration.get("declaration");
  21. const standaloneDeclaration = declaration.isFunctionDeclaration() || declaration.isClassDeclaration();
  22. const exportExpr = declaration.isFunctionExpression() || declaration.isClassExpression();
  23. const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
  24. let id = declaration.node.id;
  25. let needBindingRegistration = false;
  26. if (!id) {
  27. needBindingRegistration = true;
  28. id = scope.generateUidIdentifier("default");
  29. if (standaloneDeclaration || exportExpr) {
  30. declaration.node.id = cloneNode(id);
  31. }
  32. } else if (exportExpr && scope.hasBinding(id.name)) {
  33. needBindingRegistration = true;
  34. id = scope.generateUidIdentifier(id.name);
  35. }
  36. const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
  37. const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
  38. exportDeclaration.insertAfter(updatedExportDeclaration);
  39. exportDeclaration.replaceWith(updatedDeclaration);
  40. if (needBindingRegistration) {
  41. scope.registerDeclaration(exportDeclaration);
  42. }
  43. return exportDeclaration;
  44. } else if (exportDeclaration.get("specifiers").length > 0) {
  45. throw new Error("It doesn't make sense to split exported specifiers.");
  46. }
  47. const declaration = exportDeclaration.get("declaration");
  48. const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
  49. const specifiers = Object.keys(bindingIdentifiers).map(name => {
  50. return exportSpecifier(identifier(name), identifier(name));
  51. });
  52. const aliasDeclar = exportNamedDeclaration(null, specifiers);
  53. exportDeclaration.insertAfter(aliasDeclar);
  54. exportDeclaration.replaceWith(declaration.node);
  55. return exportDeclaration;
  56. }
  57. //# sourceMappingURL=index.js.map