vite-plugin-virtual

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

Vite plugin providing virtual modules with HMR invalidation support. Version 0.5.0, actively maintained, works with Vite 2–7. Unlike @rollup/plugin-virtual, this plugin integrates with Vite's Hot Module Replacement and allows updating or invalidating virtual module content at runtime during development. Supports ESM and TypeScript via ambient type declarations.

error SyntaxError: Cannot use import statement outside a module
cause Using ESM import in a CommonJS context without configuring type:module in package.json or using .mjs extension.
fix
Set package.json type field to "module", rename file to .mjs, or use a bundler that supports ES modules.
error TypeError: virtual is not a function
cause Called the default import incorrectly (e.g., used require() or imported a named export as default).
fix
Ensure you are using import virtual from 'vite-plugin-virtual' (default import).
error Cannot find module 'vite-plugin-virtual'
cause Package not installed or not in node_modules.
fix
Run 'npm install -D vite-plugin-virtual' in your project directory.
gotcha The plugin uses ESM-only distribution. Attempting to require() it will fail with ERR_REQUIRE_ESM.
fix Use import syntax instead of require().
gotcha updateVirtualModule and invalidateVirtualModule are exported as named exports only; there is no default export for them.
fix Use destructured import: import { updateVirtualModule } from 'vite-plugin-virtual'.
gotcha Virtual module names must be unique across the plugin instance and not conflict with other vite-resolved modules.
fix Prefix virtual modules with 'virtual:' to avoid collisions.
npm install vite-plugin-virtual
yarn add vite-plugin-virtual
pnpm add vite-plugin-virtual

Creates virtual modules 'virtual:module' and 'virtual:config' and registers them as a Vite plugin.

import virtual from 'vite-plugin-virtual'

export default {
  plugins: [
    virtual({
      'virtual:module': `export default { hello: 'world' }`,
      'virtual:config': { hello: 'world' }
    })
  ]
}

// In your source files:
// import obj from 'virtual:config'
// console.log(obj)