index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
  23. let id = declaration.node.id;
  24. let needBindingRegistration = false;
  25. if (!id) {
  26. needBindingRegistration = true;
  27. id = scope.generateUidIdentifier("default");
  28. if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) {
  29. declaration.node.id = cloneNode(id);
  30. }
  31. }
  32. const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
  33. const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
  34. exportDeclaration.insertAfter(updatedExportDeclaration);
  35. exportDeclaration.replaceWith(updatedDeclaration);
  36. if (needBindingRegistration) {
  37. scope.registerDeclaration(exportDeclaration);
  38. }
  39. return exportDeclaration;
  40. } else if (exportDeclaration.get("specifiers").length > 0) {
  41. throw new Error("It doesn't make sense to split exported specifiers.");
  42. }
  43. const declaration = exportDeclaration.get("declaration");
  44. const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
  45. const specifiers = Object.keys(bindingIdentifiers).map(name => {
  46. return exportSpecifier(identifier(name), identifier(name));
  47. });
  48. const aliasDeclar = exportNamedDeclaration(null, specifiers);
  49. exportDeclaration.insertAfter(aliasDeclar);
  50. exportDeclaration.replaceWith(declaration.node);
  51. return exportDeclaration;
  52. }