index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var core = require('@babel/core');
  3. const addJSXAttribute = (api, opts) => {
  4. const getAttributeValue = (value, literal) => {
  5. if (typeof value === "string" && literal) {
  6. return core.types.jsxExpressionContainer(
  7. core.template.ast(value).expression
  8. );
  9. }
  10. if (typeof value === "string") {
  11. return core.types.stringLiteral(value);
  12. }
  13. if (typeof value === "boolean") {
  14. return core.types.jsxExpressionContainer(core.types.booleanLiteral(value));
  15. }
  16. if (typeof value === "number") {
  17. return core.types.jsxExpressionContainer(core.types.numericLiteral(value));
  18. }
  19. return null;
  20. };
  21. return {
  22. visitor: {
  23. JSXAttribute(path) {
  24. const valuePath = path.get("value");
  25. if (!valuePath.isStringLiteral())
  26. return;
  27. opts.values.forEach(({ value, newValue, literal }) => {
  28. if (!valuePath.isStringLiteral({ value }))
  29. return;
  30. const attributeValue = getAttributeValue(newValue, literal);
  31. if (attributeValue) {
  32. valuePath.replaceWith(attributeValue);
  33. }
  34. });
  35. }
  36. }
  37. };
  38. };
  39. module.exports = addJSXAttribute;
  40. //# sourceMappingURL=index.js.map