replace-reference-identifier.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. const isShorthandPropertyValue = require('../utils/is-shorthand-property-value.js');
  3. const isShorthandPropertyAssignmentPatternLeft = require('../utils/is-shorthand-property-assignment-pattern-left.js');
  4. const isShorthandImportLocal = require('../utils/is-shorthand-import-local.js');
  5. const isShorthandExportLocal = require('../utils/is-shorthand-export-local.js');
  6. function replaceReferenceIdentifier(identifier, replacement, fixer) {
  7. if (
  8. isShorthandPropertyValue(identifier)
  9. || isShorthandPropertyAssignmentPatternLeft(identifier)
  10. ) {
  11. return fixer.replaceText(identifier, `${identifier.name}: ${replacement}`);
  12. }
  13. if (isShorthandImportLocal(identifier)) {
  14. return fixer.replaceText(identifier, `${identifier.name} as ${replacement}`);
  15. }
  16. if (isShorthandExportLocal(identifier)) {
  17. return fixer.replaceText(identifier, `${replacement} as ${identifier.name}`);
  18. }
  19. // `typeAnnotation`
  20. if (identifier.typeAnnotation) {
  21. return fixer.replaceTextRange(
  22. [identifier.range[0], identifier.typeAnnotation.range[0]],
  23. `${replacement}${identifier.optional ? '?' : ''}`,
  24. );
  25. }
  26. return fixer.replaceText(identifier, replacement);
  27. }
  28. module.exports = replaceReferenceIdentifier;