codegen.macro
raw JSON → 4.1.0 verified Sat Apr 25 auth: no javascript
codegen.macro v4.1.0 is a Babel macro that enables compile-time code generation using babel-plugin-macros. It allows you to write code that generates other code at build time, typically by evaluating a template literal or invoking a function that produces source code as a string. This is useful for metaprogramming, generating repetitive code, or embedding dynamic values into static output. Unlike babel-plugin-codegen, which requires direct Babel plugin configuration, codegen.macro works within any project that has babel-plugin-macros configured, making it easier to adopt in existing setups. It ships TypeScript types and has minimal dependencies. The package is stable and follows a low release cadence.
Common errors
error codegen.macro: Macro not found. Did you forget to install babel-plugin-macros? ↓
cause babel-plugin-macros is not installed or configured in Babel.
fix
Install babel-plugin-macros and add it to your Babel config (e.g., in .babelrc or babel.config.js).
error codegen: The code inside the template literal is not valid JavaScript. ↓
cause The string inside the tagged template literal contains syntax errors.
fix
Ensure the generated code is syntactically correct JavaScript.
Warnings
gotcha The import must be exactly `import codegen from 'codegen.macro'`. Using different import styles or paths will not trigger the macro. ↓
fix Ensure the import statement matches the expected syntax and that babel-plugin-macros is properly configured.
gotcha The generated code must use CommonJS module.exports to export values, as the macro evaluates the string as a Node.js script. ↓
fix Use `module.exports = ...` inside the generated code string.
deprecated All APIs from babel-plugin-codegen are available but the macro only supports a subset. Refer to the babel-plugin-codegen snapshots for full API. ↓
fix Check babel-plugin-codegen documentation for alternative APIs if needed.
Install
npm install codegen.macro yarn add codegen.macro pnpm add codegen.macro Imports
- default (codegen) wrong
const codegen = require('codegen.macro')correctimport codegen from 'codegen.macro' - codegen used as template literal tag
codegen`// some generated code` - codegen used as function call wrong
codegen('./generator.js') // This is validcorrectcodegen('./generator.js')
Quickstart
import codegen from 'codegen.macro'
const name = 'World'
// Generate a greeting at build time
codegen`
const greeting = 'Hello, ${name}!'
module.exports = greeting
`
// The above will be replaced during build with: const greeting = 'Hello, World!'