Registry / devops / babel-plugin-codegen

babel-plugin-codegen

JSON →
library4.1.5jsnpmunverified

Babel-plugin-codegen is a build-time code generation utility for JavaScript and TypeScript projects, currently at stable version 4.1.5. It enables developers to execute synchronous Node.js code during the Babel compilation step, replacing sections of source code with the string output of that execution. Unlike `babel-plugin-preval`, which replaces values, `babel-plugin-codegen` replaces entire code blocks by transforming the generated string into an Abstract Syntax Tree (AST) node. It can be used directly as a Babel plugin or integrated via `babel-plugin-macros` for a more flexible, macro-style API, supporting template literals, special `codegen:` import comments, and `codegen.require()` calls. The package has a slow release cadence, with the last update in September 2021, suggesting a maintenance phase focusing on stability and bug fixes rather than active feature development. This tool is particularly useful for generating boilerplate, adapting to environmental configurations, or consolidating dynamic code into static bundles during the build process, reducing runtime overhead.

npm install babel-plugin-codegen
INSTALL
IMPORT
SIG · BABEL-PLUGIN-CODEG
B
babel-plugin-codegen
devopsjavascriptv4.1.5
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.

codegen
import codegen from 'babel-plugin-codegen/macro';
const codegen = require('babel-plugin-codegen/macro');
This is the macro import for using the `codegen` template literal and `codegen.require()` API. Requires `babel-plugin-macros` to be installed and configured in your Babel setup. CommonJS `require` syntax is typically not transformed by `babel-plugin-macros`.
GeneratedModule
import GeneratedModule from 'codegen:./path/to/script.js';
import GeneratedModule from './path/to/script.js';
This special `codegen:` import comment syntax tells the plugin to execute the specified script at build time and replace the import with the script's `module.exports` string content. The `codegen:` prefix is crucial.
Babel Plugin Configuration
module.exports = { plugins: ['babel-plugin-codegen'] };
To enable `babel-plugin-codegen` as a standard Babel plugin (without `babel-plugin-macros`), add its string name to your Babel configuration's `plugins` array. This does not involve a JavaScript `import` statement in your source code.

This quickstart demonstrates how to use `babel-plugin-codegen` via its macro API to include external TypeScript code into your main file at build time. It shows the necessary Babel configuration, a source file whose content will be 'codegenned,' and how the main application file uses the `codegen` macro to perform the build-time code injection and subsequent usage.

{ "// babel.config.js": "", "module.exports": "{\n plugins: [\n 'babel-plugin-macros', // Required to use `codegen/macro`\n // Alternatively, 'babel-plugin-codegen' if not using the macro\n ],\n presets: [\n '@babel/preset-typescript',\n ['@babel/preset-env', { targets: { node: 'current' } }],\n ],\n};", "// src/dynamic-data.ts": "", "export const GREETING = \"Hello from codegen!\";\nexport function getCurrentTime(): string {\n return new Date().toLocaleTimeString();\n}\n", "// src/index.ts": "", "import codegen from 'babel-plugin-codegen/macro';\nimport * as path from 'path';\n\n// This entire `codegen` block will be replaced at build time\n// with the content of `src/dynamic-data.ts`.\ncodegen`\n const fs = require('fs');\n const pathToCode = path.resolve(__dirname, './dynamic-data.ts');\n const fileContent = fs.readFileSync(pathToCode, 'utf8');\n // The script's module.exports becomes the replacement code.\n module.exports = fileContent;\n`;\n\n// After Babel processing, the above codegen block is replaced, and\n// these generated exports become directly available in the file.\nconsole.log(GREETING); // "Hello from codegen!"\nconsole.log(`Current time generated: ${getCurrentTime()}`);\n\n// To compile and run:\n// 1. npm install --save-dev @babel/cli @babel/core @babel/preset-env @babel/preset-typescript babel-plugin-codegen babel-plugin-macros\n// 2. npx babel src/index.ts --out-file dist/index.js --extensions ".ts"\n// 3. node dist/index.js" }
Debug
Known issues
breakingVersion 4.0.0 dropped support for Node.js 8. Projects using this version or newer must run on Node.js 10 or higher.
fix
Upgrade your Node.js environment to version 10 or newer.
affects: >=4.0.0
breakingStarting with version 3.0.0, `babel-plugin-codegen` no longer transpiles the code that is being generated. The code produced by your codegen script must be valid for your target environment, or you must transpile it ahead of time.
fix
Ensure the string output by your `codegen` script is valid JavaScript for your target environment, or preprocess the generated code if it requires further transpilation (e.g., modern syntax for older browsers).
affects: >=3.0.0
gotchaAll code executed by `babel-plugin-codegen` must run synchronously. Asynchronous operations (e.g., `async/await`, Promises) are not supported within the codegen script itself.
fix
Rewrite any logic within your codegen scripts to be entirely synchronous. If external data is needed, fetch it as part of your build process *before* Babel runs, or use synchronous file I/O operations.
affects: all
gotchaCode run by `babel-plugin-codegen` is executed in a non-sandboxed Node.js environment. Be cautious when using third-party scripts or untrusted input, as they could execute arbitrary code with the same privileges as your build process.
fix
Only execute trusted code within your `codegen` scripts. Review any external scripts or user-provided input that contributes to the codegen process for potential security vulnerabilities.
affects: all
gotchaWhen using `babel-plugin-codegen/macro`, `babel-plugin-macros` must be explicitly installed and configured in your Babel setup, otherwise the `codegen` macro syntax will not be recognized.
fix
Install `babel-plugin-macros` as a development dependency (`npm install --save-dev babel-plugin-macros`) and add it to your Babel configuration's `plugins` array (e.g., `plugins: ['babel-plugin-macros']`).
affects: all
Errors
Common errors & fixes
ReferenceError: codegen is not defined
The `codegen` template tag or `codegen.require` was used, but the `babel-plugin-codegen/macro` is not active, or the main `babel-plugin-codegen` is not configured.
fix
If using the macro, install `babel-plugin-macros` (`npm i -D babel-plugin-macros`) and add it to your Babel configuration's `plugins` array. If using the plugin directly, ensure 'babel-plugin-codegen' is in your Babel plugins.
Error: Cannot find module './some-code.js'
File system operations like `require.resolve()` or `fs.readFileSync()` within the codegen script are executed at *build time* from the Node.js context where Babel runs, not relative to the source file.
fix
Use absolute paths or resolve paths relative to `__dirname` within your codegen script (e.g., `path.resolve(__dirname, './some-code.js')`) to ensure correct file resolution from the Babel execution context.
SyntaxError: Unexpected token 'export' (or 'import')
The code generated by the `codegen` script produces module syntax (e.g., `export` or `import`) that is incompatible with the module system of the file it's inserted into, or with subsequent Babel transforms.
fix
Ensure the *output* string from your codegen script produces valid JavaScript/TypeScript for its final insertion context. If the target file is an ESM module, the codegen script should output ESM syntax (`export ...`). Verify your Babel presets handle the generated module syntax correctly.
Upgrade
Version history
4.1.5latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
8 hits · last 30 days
node
8
Resources