utils.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  6. exports.getImportSource = getImportSource;
  7. exports.createDynamicImportTransform = createDynamicImportTransform;
  8. function getImportSource(t, callNode) {
  9. var importArguments = callNode.arguments;
  10. var _importArguments = _slicedToArray(importArguments, 1),
  11. importPath = _importArguments[0];
  12. var isString = t.isStringLiteral(importPath) || t.isTemplateLiteral(importPath);
  13. if (isString) {
  14. t.removeComments(importPath);
  15. return importPath;
  16. }
  17. return t.templateLiteral([t.templateElement({ raw: '', cooked: '' }), t.templateElement({ raw: '', cooked: '' }, true)], importArguments);
  18. }
  19. function createDynamicImportTransform(_ref) {
  20. var template = _ref.template,
  21. t = _ref.types;
  22. var builders = {
  23. 'static': {
  24. interop: template('Promise.resolve().then(() => INTEROP(require(SOURCE)))'),
  25. noInterop: template('Promise.resolve().then(() => require(SOURCE))')
  26. },
  27. dynamic: {
  28. interop: template('Promise.resolve(SOURCE).then(s => INTEROP(require(s)))'),
  29. noInterop: template('Promise.resolve(SOURCE).then(s => require(s))')
  30. }
  31. };
  32. var visited = typeof WeakSet === 'function' && new WeakSet();
  33. var isString = function isString(node) {
  34. return t.isStringLiteral(node) || t.isTemplateLiteral(node) && node.expressions.length === 0;
  35. };
  36. return function (context, path) {
  37. if (visited) {
  38. if (visited.has(path)) {
  39. return;
  40. }
  41. visited.add(path);
  42. }
  43. var SOURCE = getImportSource(t, path.parent);
  44. var builder = isString(SOURCE) ? builders['static'] : builders.dynamic;
  45. var newImport = context.opts.noInterop ? builder.noInterop({ SOURCE: SOURCE }) : builder.interop({ SOURCE: SOURCE, INTEROP: context.addHelper('interopRequireWildcard') });
  46. path.parentPath.replaceWith(newImport);
  47. };
  48. }