rsbuild-plugin-virtual-module🧙

July 14, 2026 · View on GitHub

The simplest and most flexible way to build with a compiling magic 🪄

An Rsbuild plugin for generating virtual modules with async transform handlers, loaderContext APIs, and dependency-aware HMR, similar to webpack's VirtualUrlPlugin. It uses Rspack's built-in VirtualModulesPlugin under the hood.

npm version license downloads

Usage

Install:

npm add rsbuild-plugin-virtual-module -D

Add plugin to your rsbuild.config.ts:

// rsbuild.config.ts
import { pluginVirtualModule } from 'rsbuild-plugin-virtual-module';

export default {
  plugins: [
    pluginVirtualModule({
      virtualModules: {
        'virtual-foo': async () => {
          return 'export default {}';
        },
      },
    }),
  ],
};
import foo from 'virtual-foo';

console.log(foo); // {}

Options

virtualModules

Generate virtual modules, where the key is the name of the virtual module and the value is TransformHandler. See Rsbuild - api.transform

  • Type:
import type { TransformHandler } from '@rsbuild/core';

type VirtualModules = Record<string, TransformHandler>;
  • Default: {}
  • Example:
pluginVirtualModule({
  virtualModules: {
    'virtual-json-list': async ({ addDependency, addContextDependency }) => {
      const jsonFolderPath = join(__dirname, 'json');
      const ls = await readdir(jsonFolderPath);
      addContextDependency(jsonFolderPath);

      const res: Record<string, unknown> = {};
      for (const file of ls) {
        if (file.endsWith('.json')) {
          const jsonFilePath = join(jsonFolderPath, file);
          const jsonContent = await readFile(jsonFilePath, 'utf-8');
          addDependency(jsonFilePath);
          res[file] = JSON.parse(jsonContent);
        }
      }

      return `export default ${JSON.stringify(res)}`;
    },
  },
});
import jsonList from 'virtual-json-list';
console.log(jsonList);

tempDir

The name of the virtual module folder based on api.context.rootPath

  • Type: string
  • Default: .rsbuild-virtual-module
  • Example:
pluginVirtualModule({
  tempDir: 'src',
  virtualModules: {
    'virtual-foo': async () => {
      return 'export default {}';
    },
  },
});

The actual virtual module is ./src/virtual-foo.js

What's the difference from Rspack's VirtualModulesPlugin?

Rspack's built-in VirtualModulesPlugin accepts source strings and provides writeModule for imperative updates.

This plugin is closer to webpack's VirtualUrlPlugin: an async TransformHandler generates the module and exposes loaderContext APIs such as addDependency and addContextDependency to track changes and trigger HMR.

License

MIT.