Vite Plugin Codegen

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

A Vite plugin (v4+) that generates virtual modules at bundle time, useful for injecting configuration, metadata, or generated code without a separate build step. Current stable version is 2.1.0, with monthly releases. Ships TypeScript types. Supports ESM-only; designed specifically for Vite 4+. Key differentiator: generates virtual modules on-the-fly, eliminating the need for pre-build scripts or file I/O.

error Error: [vite-plugin-codegen] Virtual module id must start with 'virtual:'
cause Module ID missing the required prefix.
fix
Add 'virtual:' prefix to the module id.
error TypeError: codegen is not a function
cause Using default import (common mistake after v2 breaking change).
fix
Change to named import: import { codegen } from 'vite-plugin-codegen'.
error Error: require() of ES Module not supported
cause CJS require() used for ESM-only package.
fix
Switch to ESM imports or set project type to module in package.json.
breaking v2.0.0 moved core logic to 'codegen-lib' and restructured exports; default import removed.
fix Use named import: import { codegen } from 'vite-plugin-codegen'.
gotcha Virtual module IDs must be prefixed with 'virtual:' or the plugin will not resolve them.
fix Use 'virtual:' prefix for all generated module ids.
gotcha Only ESM output is supported; CJS require() will fail.
fix Use ESM imports or ensure your project is configured for ESM.
deprecated The old 'generate' function signature from v1 is removed; use the new object format with 'id' and 'generate'.
fix Update plugin configuration to new object format.
npm install vite-plugin-codegen
yarn add vite-plugin-codegen
pnpm add vite-plugin-codegen

Shows how to configure the plugin in vite.config.ts and use a generated virtual module in app code.

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

export default defineConfig({
  plugins: [
    codegen({
      modules: [
        {
          id: 'my-module',
          generate: () => `export const message = 'Hello, World!';`
        }
      ]
    })
  ]
});

// In your application code, import the virtual module:
// import { message } from 'virtual:my-module';