babel-plugin-macros is a Babel plugin that enables the creation of compile-time code transformations through a standard, convention-based interface, eliminating the need for users to configure individual Babel plugins for each library that offers such optimizations. It allows libraries to provide compile-time benefits (like CSS-in-JS style extraction or GraphQL fragment compilation) by detecting imports ending with `.macro` and processing them. The current stable version is 3.1.0, released in May 2021. While not frequently updated, it remains a foundational tool, notably integrated into popular frameworks like Create React App. Its key differentiator is simplifying the developer experience by centralizing build-time transformations under a single Babel plugin configuration, making compile-time optimizations more accessible and easier to manage.
npm install babel-plugin-macrosVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define and use a simple `log.macro` to perform compile-time logging and remove the macro calls from the final bundle, showcasing the core concept of compile-time code transformation.
Upgrade Node.js to version 10 or higher, or pin `babel-plugin-macros` to a version below 3.0.0.
Review macro configuration files (`.babel-plugin-macrosrc.*`, `babelMacros` in `package.json`) and ensure they are correctly resolved by `cosmiconfig`'s updated logic. Test thoroughly after upgrading.
Ensure all macro logic is synchronous and operates only on static values or the AST provided. For dynamic runtime data, process it outside the macro or pass it as static arguments.
To force a recompile during development, add a 'cache busting' comment to the file using the macro (e.g., `// force recompile`). Alternatively, clear Babel's cache (e.g., `rm -rf node_modules/.cache/babel-loader`). This issue is being worked on by Babel core.
Ensure that any imports intended to be processed by `babel-plugin-macros` explicitly include the `.macro` suffix in their path, e.g., `import MyMacro from './my-macro.macro';`
Install `babel-plugin-macros` (`npm install --save-dev babel-plugin-macros`) and add it to your Babel configuration's `plugins` array: `plugins: ['macros']`. If using Create React App, it often works out of the box.
Check the macro's documentation for any required configuration settings. Ensure the `configName` provided to `createMacro` (if applicable) matches the name used in your `babel-plugin-macros.config.js` or `package.json`'s `babelMacros` field. Verify the macro file itself is correctly located and exports a `createMacro` function.