no-unnecessary-trans.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. module.exports = {
  2. meta: {
  3. type: 'problem',
  4. fixable: 'code',
  5. docs: {
  6. description: 'Prohibit Trans with no components or values',
  7. },
  8. },
  9. create(context) {
  10. return {
  11. 'JSXOpeningElement[name.name="Trans"]'(node) {
  12. const attributes = new Map(
  13. node.attributes.map(attr => [attr.name.name, attr])
  14. )
  15. if (!attributes.has('components')) {
  16. if (node.parent.children.length > 0) {
  17. context.report({
  18. node,
  19. message: `Trans components must not have child elements`,
  20. })
  21. } else if (attributes.has('values')) {
  22. context.report({
  23. node,
  24. message: `Use t('…') when there are no components`,
  25. })
  26. } else {
  27. context.report({
  28. node,
  29. message: `Use t('…') when there are no components`,
  30. fix(fixer) {
  31. const i18nKey = attributes.get('i18nKey').value.value
  32. // Note: Prettier can fix indentation
  33. return fixer.replaceText(node.parent, `{t('${i18nKey}')}`)
  34. },
  35. })
  36. }
  37. }
  38. },
  39. }
  40. },
  41. }