esbuild-codegen-plugin
raw JSON → 2.1.0 verified Fri May 01 auth: no javascript
An esbuild plugin (v2.1.0) for generating modules at bundle time, allowing dynamic code injection during builds. Part of the codegen-js monorepo, it provides a core library (`codegen-lib`) and loaders for esbuild, webpack, parcel, and bun. Supports both ESM and CJS output. Key differentiator: code generation at bundle time rather than pre-build scripts, enabling type-safe dynamic imports and real-time code generation based on build context. Released monthly with active maintenance.
Common errors
error Error: Cannot find module 'esbuild-codegen-plugin' ↓
cause Package not installed or resolution failure.
fix
Run npm install esbuild-codegen-plugin --save-dev
error TypeError: esbuildCodegenPlugin is not a function ↓
cause Using default import destructured incorrectly or using require with v2+.
fix
Use import { esbuildCodegenPlugin } from 'esbuild-codegen-plugin' (ESM only).
error Error: Plugin must be an object with name and setup, got function ↓
cause Passing the plugin function incorrectly (e.g., without calling it).
fix
Call the function: esbuildCodegenPlugin({...}) and pass its return value to plugins array.
Warnings
breaking v2.0.0 dropped CommonJS support — require() now throws. ↓
fix Switch to ESM imports: import { esbuildCodegenPlugin } from 'esbuild-codegen-plugin'.
gotcha Generated module paths must be relative to project root, not absolute. ↓
fix Use paths like './my-module.ts' instead of '/absolute/path/my-module.ts'.
gotcha Plugin runs during build but before resolve — ensure generated modules don't conflict with existing files. ↓
fix Use unique paths or namespaced prefixes for generated modules.
deprecated The 'generate' function from v1.x is removed; use the plugin constructor directly. ↓
fix Replace generate(config)(esbuildConfig) with esbuildCodegenPlugin(config) in plugin array.
Install
npm install esbuild-codegen-plugin yarn add esbuild-codegen-plugin pnpm add esbuild-codegen-plugin Imports
- esbuildCodegenPlugin wrong
const esbuildCodegenPlugin = require('esbuild-codegen-plugin')correctimport { esbuildCodegenPlugin } from 'esbuild-codegen-plugin' - default wrong
import { default as esbuildCodegenPlugin } from 'esbuild-codegen-plugin'correctimport esbuildCodegenPlugin from 'esbuild-codegen-plugin' - PluginConfig wrong
import { PluginConfig } from 'esbuild-codegen-plugin'correctimport type { PluginConfig } from 'esbuild-codegen-plugin'
Quickstart
import { build } from 'esbuild';
import { esbuildCodegenPlugin } from 'esbuild-codegen-plugin';
import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
await build({
entryPoints: ['./src/app.ts'],
bundle: true,
outfile: './dist/bundle.js',
plugins: [
esbuildCodegenPlugin({
// Generate a module that exports current build time
'./build-time.ts': `export const buildTime = ${JSON.stringify(Date.now())};`,
}),
],
});