TemplateLiteral.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = extractValueFromTemplateLiteral;
  6. function sortStarts(a, b) {
  7. return (a.range ? a.range[0] : a.start) - (b.range ? b.range[0] : b.start);
  8. }
  9. /**
  10. * Returns the string value of a template literal object.
  11. * Tries to build it as best as it can based on the passed
  12. * prop. For instance `This is a ${prop}` will return 'This is a {prop}'.
  13. *
  14. * If the template literal builds to undefined (`${undefined}`), then
  15. * this should return "undefined".
  16. */
  17. function extractValueFromTemplateLiteral(value) {
  18. var quasis = value.quasis,
  19. expressions = value.expressions;
  20. var partitions = quasis.concat(expressions);
  21. return partitions.sort(sortStarts).map(function (_ref) {
  22. var type = _ref.type,
  23. _ref$value = _ref.value;
  24. _ref$value = _ref$value === undefined ? {} : _ref$value;
  25. var raw = _ref$value.raw,
  26. name = _ref.name;
  27. if (type === 'TemplateElement') {
  28. return raw;
  29. }
  30. if (type === 'Identifier') {
  31. return name === 'undefined' ? name : '{' + name + '}';
  32. }
  33. if (type.indexOf('Expression') > -1) {
  34. return '{' + type + '}';
  35. }
  36. return '';
  37. }).join('');
  38. }