kentcdodds / babel-plugin-macros

🎣 Allows you to build simple compile-time libraries
https://npm.im/babel-plugin-macros
MIT License
2.62k stars 135 forks source link

Macros are not applied if they are not the default export #151

Closed vedantroy closed 4 years ago

vedantroy commented 4 years ago

Relevant code:

src/macro.js (this file is compiled to "dist/macro.js" with "@babel/plugin-transform-modules-commonjs"):

import { createMacro } from "babel-plugin-macros"

function gemmafyMacro({references, state, babel}) {
  references.default.forEach(referencePath => {
      // do macro stuff
  })
}

export default createMacro(gemmafyMacro)
const gemmafyCopy = createMacro(gemmafyMacro)
export {gemmafyCopy}

test.js:

// compiled with the plugins: 
// babel-plugin-macros, @babel/plugin-transform-modules-commonjs
import gemmafy, {gemmafyCopy} from '../dist/macro'

gemmafy("Hello World");
gemmafyCopy("Hello World");

test_compiled.js:

"use strict";

"Hello \uD83D\uDC36 World";
gemmafyCopy("Hello World"); // the macro was not applied here

What happened:

Only gemmafy was applied. gemmafyCopy was not applied.

Reproduction repository: https://github.com/vedantroy/babel-plugin-macros-repro

Run npm run build-macro and then npm run build-test. Then look at test_compiled.js in the "tests" folder. You will see that only 1 of the macros has been applied.

Problem description:

Macros are not applied, unless they are the default export?

Suggested solution: Not sure. If this is a bug, I'd be willing to look into a PR.

kentcdodds commented 4 years ago

Hi @vedantroy,

The macro must be the default export. If you want to transform non-default exports then use the references object.

import { createMacro } from "babel-plugin-macros"

function gemmafyMacro({references, state, babel}) {
  references.default.forEach(referencePath => {
      // do macro stuff
  })
  references.gemmafyCopy.forEach(referencePath => {
      // do macro stuff for the named import
  })
}

export default createMacro(gemmafyMacro)

See the documentation for more info.

vedantroy commented 4 years ago

Oh, I'm silly! I should get better at reading docs :facepalm: