dynamic-import.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.buildDynamicImport = buildDynamicImport;
  6. exports.getDynamicImportSource = getDynamicImportSource;
  7. var t = require("@babel/types");
  8. var _template = require("@babel/template");
  9. function getDynamicImportSource(node) {
  10. const [source] = node.arguments;
  11. return t.isStringLiteral(source) || t.isTemplateLiteral(source) ? source : _template.default.expression.ast`\`\${${source}}\``;
  12. }
  13. function buildDynamicImport(node, deferToThen, wrapWithPromise, builder) {
  14. const [specifier] = node.arguments;
  15. if (t.isStringLiteral(specifier) || t.isTemplateLiteral(specifier) && specifier.quasis.length === 0) {
  16. if (deferToThen) {
  17. return _template.default.expression.ast`
  18. Promise.resolve().then(() => ${builder(specifier)})
  19. `;
  20. } else return builder(specifier);
  21. }
  22. const specifierToString = t.isTemplateLiteral(specifier) ? t.identifier("specifier") : t.templateLiteral([t.templateElement({
  23. raw: ""
  24. }), t.templateElement({
  25. raw: ""
  26. })], [t.identifier("specifier")]);
  27. if (deferToThen) {
  28. return _template.default.expression.ast`
  29. (specifier =>
  30. new Promise(r => r(${specifierToString}))
  31. .then(s => ${builder(t.identifier("s"))})
  32. )(${specifier})
  33. `;
  34. } else if (wrapWithPromise) {
  35. return _template.default.expression.ast`
  36. (specifier =>
  37. new Promise(r => r(${builder(specifierToString)}))
  38. )(${specifier})
  39. `;
  40. } else {
  41. return _template.default.expression.ast`
  42. (specifier => ${builder(specifierToString)})(${specifier})
  43. `;
  44. }
  45. }
  46. //# sourceMappingURL=dynamic-import.js.map