Description
Currently, CRA only supports babel macros when they are in the application's code. It doesn't support macros on dependencies.
Is your proposal related to a problem?
Yes.
I have an internal library meant to be used by several React applications.
This library uses the babel plugin "preval" through a babel macro to transform its code at build-time. These transformations can't happen when building the library; they need to happen when building the application because they depend on the application's environmental variables.
Unfortunately, I can't use this library on CRA applications without ejecting.
Here's a code example:
node_modules/my-library/index.js
import preval from 'babel-plugin-preval/macro'
// complex computation based on environmental variables
export const one = preval`module.exports = 1 + 2 - 1 - 1`
src/App.js
import React from 'react';
import { one } from 'my-library';
function App() {
return <div>The number: {one}</div>;
}
export default App;
This produces the following error: MacroError: The macro you imported from “undefined” is being executed outside the context of compilation with babel-plugin-macros.
Describe the solution you'd like
This could be solved by adding babel-plugin-macros
to the list of plugins on packages/babel-preset-react-app/dependencies.js
.
Currently, babel-plugin-macros
is present only on packages/babel-preset-react-app/create.js
.
Additional context
Related issues, PRs, and resources:
- RFC - babel-macros #2730
- add experimental babel-plugin-macros support #3675
- All about macros with babel-plugin-macros - Video by @kentcdodds
This pattern works in Gatsby, but I couldn't find documentation about it, so I don't know if it's officially supported. Here's the relevant PR: