rollup-plugin-codegen

raw JSON →
2.1.0 verified Mon Apr 27 auth: no javascript

A Rollup plugin for generating source code modules at bundle time. Current stable version is 2.1.0, released with fixes and support for Bun and Parcel loaders. This plugin allows dynamic generation of modules based on configuration, useful for injecting environment variables, version info, or computed code. Key differentiator: it integrates directly into Rollup's build process, avoiding separate pre-build steps. Ships TypeScript types, supports ESM and CJS outputs, requires Node >=16.0. Alternative to virtual modules or manual file writes.

error Error: The plugin 'codegen' does not export a default export.
cause Using default import instead of named import in ESM environment.
fix
Change import codegen from 'rollup-plugin-codegen' to import { codegen } from 'rollup-plugin-codegen'
error Error: Cannot find module 'rollup-plugin-codegen'
cause Package not installed or not in node_modules.
fix
Run npm install rollup-plugin-codegen or yarn add rollup-plugin-codegen.
error Error: The generated module 'src/env' could not be resolved.
cause The module ID path does not match Rollup's resolution or file system.
fix
Ensure the module id is a relative path that does not conflict with existing files. Use a path like 'src/generated/env' that doesn't exist on disk.
breaking Version 2.0.0 changed from default export to named export
fix Use `import { codegen } from 'rollup-plugin-codegen'` instead of `import codegen from 'rollup-plugin-codegen'`
breaking Node version requirement changed to >=16.0
fix Upgrade Node.js to version 16 or later.
gotcha Generated module IDs must be relative and unique; duplicate IDs cause errors
fix Ensure each module id is a unique relative path string (e.g., 'src/generated/env').
npm install rollup-plugin-codegen
yarn add rollup-plugin-codegen
pnpm add rollup-plugin-codegen

Shows how to configure codegen plugin to generate a module with environment variable.

import { codegen } from 'rollup-plugin-codegen';
import { defineConfig } from 'rollup';

export default defineConfig({
  input: 'src/index.js',
  plugins: [
    codegen({
      modules: [
        {
          id: 'src/env',
          code: `export const NODE_ENV = ${JSON.stringify(process.env.NODE_ENV ?? 'development')};`
        }
      ]
    })
  ],
  output: { dir: 'dist', format: 'esm' }
});