Registry / web-framework / babel-plugin-macros

babel-plugin-macros

JSON →
library3.1.0jsnpmunverified

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-macros
INSTALL
IMPORT
SIG · BABEL-PLUGIN-MACRO
B
babel-plugin-macros
web-frameworkjavascriptv3.1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MyMacro
import MyMacro from './path/to/my.macro';
import MyMacro from './path/to/my';
Users consume macros by importing them with a `.macro` suffix (e.g., `my.macro`, `my/macro`). This suffix signals `babel-plugin-macros` to intercept and transform the import at compile time. Omitting it will result in a standard module import, bypassing macro processing.
createMacro
import { createMacro } from 'babel-plugin-macros';
const { createMacro } = require('babel-plugin-macros');
Macro authors use `createMacro` to define their macro logic. While `require` works for CommonJS macro files, `import` is generally preferred in modern JavaScript. The `createMacro` function wraps the macro's core logic, providing it with Babel AST references, state, and a Babel instance.
ConfiguredMacro
import ConfiguredMacro from 'configured-lib.macro';
Macros can be configured via a `babel-plugin-macros.config.js` file or `babelMacros` entry in `package.json`. This allows macros to receive specific options without requiring per-macro Babel plugin configuration.

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.

/* .babelrc.js */ module.exports = { plugins: ['babel-plugin-macros'], }; /* log.macro.js */ const { createMacro } = require('babel-plugin-macros'); module.exports = createMacro(({ references, state, babel }) => { // console.log('[log.macro] Running macro for file:', state.file.opts.filename); references.default.forEach(referencePath => { if (referencePath.parentPath.type === 'CallExpression') { const args = referencePath.parentPath.node.arguments; const messages = args.map(arg => { // Only process string and numeric literals for simplicity in quickstart if (babel.types.isStringLiteral(arg) || babel.types.isNumericLiteral(arg)) { return arg.value; } else if (babel.types.isIdentifier(arg)) { return `[runtime_value: ${arg.name}]`; // Indicate it's a runtime value } return 'unknown_type'; }); console.log(`[log.macro] Compiling-time log: ${messages.join(', ')}`); // Replace the macro call with `undefined` to remove it from runtime bundle referencePath.parentPath.replaceWith(babel.types.valueToNode(undefined)); } else { // Handle other types of references if necessary, or throw an error throw new Error(`log.macro can only be called as a function.`); } }); }); /* app.js */ import log from './log.macro'; log('Hello', 'world', 123); // This will be logged at compile time const runtimeVar = 'dynamic message'; log('This part is static:', runtimeVar); // `runtimeVar` will be treated as '[runtime_value: runtimeVar]' console.log('Runtime code runs after macro transformations.'); // To run: // 1. npm install --save-dev @babel/cli @babel/core babel-plugin-macros // 2. npx babel app.js --out-file app-compiled.js // 3. node app-compiled.js
Debug
Known issues
breakingVersion 3.0.0 updated its Node.js engine requirement to `>=10`. Projects running on older Node.js versions will need to upgrade or remain on `babel-plugin-macros` v2.x.x.
fix
Upgrade Node.js to version 10 or higher, or pin `babel-plugin-macros` to a version below 3.0.0.
affects: >=3.0.0
breakingUpdates to `cosmiconfig` in v2.6.2 and subsequent versions (including v3.0.0) might subtly change how macro configurations are resolved, particularly if custom `configName` options are used or if configuration files are in non-standard locations.
fix
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.
affects: >=2.6.2
gotchaMacros run purely at *compile-time* and cannot access runtime values or perform asynchronous operations. Any logic within a macro must be synchronous and operate solely on the Abstract Syntax Tree (AST) available during the Babel transformation step. Attempting to use runtime variables will result in compile errors or unexpected `undefined` values.
fix
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.
affects: >=1.0.0
gotchaBabel's caching mechanisms can sometimes prevent macros from re-running during development if the source file itself hasn't changed, even if the macro's internal logic or its dependencies have. This can lead to stale transformations.
fix
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.
affects: >=1.0.0
Errors
Common errors & fixes
Module not found: Error: Can't resolve './my-macro'
The imported file is a macro, but the `.macro` suffix was omitted in the import path, preventing `babel-plugin-macros` from intercepting it.
fix
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';`
ReferenceError: myMacro is not defined
The `babel-plugin-macros` plugin is not correctly installed or configured in the project's Babel configuration (`.babelrc`, `babel.config.js`).
fix
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.
Error: The macro 'my-macro' is not specified in your babel config
While `babel-plugin-macros` is configured, the specific macro being used might require additional configuration parameters, or there's a typo in the macro's name or its configuration. (Note: this specific error string might be more generic like 'Error: 'macroName' macro does not exist' depending on the exact version and usage)
fix
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.
Upgrade
Version history
3.1.0latest on npm
Audit
Dependencies
@babel/corerequiredbabel-plugin-macros is a Babel plugin and requires a Babel environment to function. While not a direct runtime dependency in the npm `dependencies` sense, `@babel/core` is a peer dependency of the Babel ecosystem and must be installed for Babel plugins to run. Macro authors also interact with `@babel/core`'s AST utilities.
Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources
babel-plugin-macros — npm install babel-plugin-macros · libregistry