index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var core = require('@babel/core');
  3. const elements = ["svg", "Svg"];
  4. const getValue = (raw) => {
  5. if (raw === void 0)
  6. return core.types.stringLiteral("1em");
  7. switch (typeof raw) {
  8. case "number":
  9. return core.types.jsxExpressionContainer(core.types.numericLiteral(raw));
  10. case "string":
  11. return core.types.stringLiteral(raw);
  12. default:
  13. return core.types.stringLiteral("1em");
  14. }
  15. };
  16. const plugin = (_, opts) => ({
  17. visitor: {
  18. JSXOpeningElement(path) {
  19. if (!elements.some(
  20. (element) => path.get("name").isJSXIdentifier({ name: element })
  21. ))
  22. return;
  23. const values = {
  24. width: getValue(opts.width),
  25. height: getValue(opts.height)
  26. };
  27. const requiredAttributes = Object.keys(values);
  28. path.get("attributes").forEach((attributePath) => {
  29. if (!attributePath.isJSXAttribute())
  30. return;
  31. const namePath = attributePath.get("name");
  32. if (!namePath.isJSXIdentifier())
  33. return;
  34. const index = requiredAttributes.indexOf(namePath.node.name);
  35. if (index === -1)
  36. return;
  37. const valuePath = attributePath.get("value");
  38. valuePath.replaceWith(values[namePath.node.name]);
  39. requiredAttributes.splice(index, 1);
  40. });
  41. path.pushContainer(
  42. "attributes",
  43. requiredAttributes.map(
  44. (attr) => core.types.jsxAttribute(
  45. core.types.jsxIdentifier(attr),
  46. values[attr]
  47. )
  48. )
  49. );
  50. }
  51. }
  52. });
  53. module.exports = plugin;
  54. //# sourceMappingURL=index.js.map