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

MacroError in NextJS when used in a package #135

Closed maktouch closed 4 years ago

maktouch commented 4 years ago

Relevant code or config

import React from 'react';
import preval from 'preval.macro';
const one = preval`module.exports = 1 + 2 - 1 - 1`;

export default function Test() {
  return (
    <div>
      {one}
    </div>
  );
}

What you did:

When this is used inside NextJS, it works correctly.

When this is extracted as a package in the monorepo, imported and used, it doesn't, with error:

MacroError: The macro you imported from "undefined" is being executed outside the context of compilation with babel-plugin-macros. This indicates that you don't have the babel plugin "babel-plugin-macros" configured correctly.

Reproduction repository:

https://github.com/maktouch/micro-frontends-poc

git clone git@github.com:maktouch/micro-frontends-poc.git
cd micro-frontends-poc
yarn 
cd nextjs
yarn dev

Problem description:

There's something fishy going on with the way Next handles this, because it works pretty much out of the box for CRA and Gatsby. The problem arose when I tried to use a component with Lingui, but it didn't work. I thought it somehow missed some Lingui magic but after investigating for the whole day, it seems like Macro + External package + Next doesn't work.

Suggested solution:

Could it be because of this module? https://github.com/martpie/next-transpile-modules.

maktouch commented 4 years ago

Figured it out, it was a bad babel config =)

wholenews commented 3 years ago

Wow thanks @maktouch, your repository finally lead me to a solution. My issue was fixed by replacing .babelrc containing:

{
  "presets": ["next/babel"],
  "plugins": ["macros"]
}

with babel.config.js containing:

module.exports = {
  presets: [require.resolve('next/babel')],
  plugins: [[require.resolve('babel-plugin-macros')]],
};