index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const { createMacro, MacroError } = require('babel-plugin-macros');
  2. const { addNamed } = require('@babel/helper-module-imports');
  3. module.exports = createMacro(gooberMacro);
  4. function gooberMacro({ references, babel, state }) {
  5. const program = state.file.path;
  6. if (references.default) {
  7. throw new MacroError('goober.macro does not support default import');
  8. }
  9. // Inject import {...} from 'goober'
  10. Object.keys(references).forEach((refName) => {
  11. const id = addNamed(program, refName, 'goober');
  12. references[refName].forEach((referencePath) => {
  13. referencePath.node.name = id.name;
  14. });
  15. });
  16. const t = babel.types;
  17. const styledReferences = references.styled || [];
  18. styledReferences.forEach((referencePath) => {
  19. const type = referencePath.parentPath.type;
  20. if (type === 'MemberExpression') {
  21. const node = referencePath.parentPath.node;
  22. const functionName = node.object.name;
  23. let elementName = node.property.name;
  24. // Support custom elements
  25. if (/[A-Z]/.test(elementName)) {
  26. elementName = elementName.replace(/[A-Z]/g, '-$&').toLowerCase();
  27. }
  28. referencePath.parentPath.replaceWith(
  29. t.callExpression(t.identifier(functionName), [t.stringLiteral(elementName)])
  30. );
  31. }
  32. });
  33. }