index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = void 0;
  4. const positionMethod = {
  5. start: 'unshiftContainer',
  6. end: 'pushContainer'
  7. };
  8. const addJSXAttribute = ({
  9. types: t,
  10. template
  11. }, opts) => {
  12. function getAttributeValue({
  13. literal,
  14. value
  15. }) {
  16. if (typeof value === 'boolean') {
  17. return t.jsxExpressionContainer(t.booleanLiteral(value));
  18. }
  19. if (typeof value === 'number') {
  20. return t.jsxExpressionContainer(t.numericLiteral(value));
  21. }
  22. if (typeof value === 'string' && literal) {
  23. return t.jsxExpressionContainer(template.ast(value).expression);
  24. }
  25. if (typeof value === 'string') {
  26. return t.stringLiteral(value);
  27. }
  28. return null;
  29. }
  30. function getAttribute({
  31. spread,
  32. name,
  33. value,
  34. literal
  35. }) {
  36. if (spread) {
  37. return t.jsxSpreadAttribute(t.identifier(name));
  38. }
  39. return t.jsxAttribute(t.jsxIdentifier(name), getAttributeValue({
  40. value,
  41. literal
  42. }));
  43. }
  44. return {
  45. visitor: {
  46. JSXOpeningElement(path) {
  47. if (!opts.elements.includes(path.node.name.name)) return;
  48. opts.attributes.forEach(({
  49. name,
  50. value = null,
  51. spread = false,
  52. literal = false,
  53. position = 'end'
  54. }) => {
  55. const method = positionMethod[position];
  56. const newAttribute = getAttribute({
  57. spread,
  58. name,
  59. value,
  60. literal
  61. });
  62. const attributes = path.get('attributes');
  63. const isEqualAttribute = attribute => {
  64. if (spread) {
  65. return attribute.get('argument').isIdentifier({
  66. name
  67. });
  68. }
  69. return attribute.get('name').isJSXIdentifier({
  70. name
  71. });
  72. };
  73. const replaced = attributes.some(attribute => {
  74. if (!isEqualAttribute(attribute)) return false;
  75. attribute.replaceWith(newAttribute);
  76. return true;
  77. });
  78. if (!replaced) {
  79. path[method]('attributes', newAttribute);
  80. }
  81. });
  82. }
  83. }
  84. };
  85. };
  86. var _default = addJSXAttribute;
  87. exports.default = _default;