getPropertyName.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import getNameOrValue from './getNameOrValue.js';
  2. import resolveToValue from './resolveToValue.js';
  3. export const COMPUTED_PREFIX = '@computed#';
  4. /**
  5. * In an ObjectExpression, the name of a property can either be an identifier
  6. * or a literal (or dynamic, but we don't support those). This function simply
  7. * returns the value of the literal or name of the identifier.
  8. */
  9. export default function getPropertyName(propertyPath) {
  10. if (propertyPath.isObjectTypeSpreadProperty()) {
  11. const argument = propertyPath.get('argument');
  12. if (argument.isGenericTypeAnnotation()) {
  13. return getNameOrValue(argument.get('id'));
  14. }
  15. return null;
  16. }
  17. else if (propertyPath.has('computed')) {
  18. const key = propertyPath.get('key');
  19. // Try to resolve variables and member expressions
  20. if (key.isIdentifier() || key.isMemberExpression()) {
  21. const valuePath = resolveToValue(key);
  22. if (valuePath.isStringLiteral() || valuePath.isNumericLiteral()) {
  23. return `${valuePath.node.value}`;
  24. }
  25. }
  26. // generate name for identifier
  27. if (key.isIdentifier()) {
  28. return `${COMPUTED_PREFIX}${key.node.name}`;
  29. }
  30. if (key.isStringLiteral() || key.isNumericLiteral()) {
  31. return `${key.node.value}`;
  32. }
  33. return null;
  34. }
  35. return `${getNameOrValue(propertyPath.get('key'))}`;
  36. }