VirtualModulesPlugin

Added in v1.5.0Rspack only

VirtualModulesPlugin allows you to create, modify, and delete files in memory, and Rspack treats these virtual files as if they were real files existing in the file system.

This plugin is a Rust implementation of webpack-virtual-modules, deeply integrated with Rspack to provide equivalent functionality with better performance.

Usage

Basic usage

When creating a VirtualModulesPlugin instance, you can directly configure virtual modules in the constructor:

import { rspack } from '@rspack/core';

new rspack.experiments.VirtualModulesPlugin({
  // ...modules
});
  • Parameters:
    • modules (optional): An object where keys are file paths and values are file contents.
rspack.config.mjs
import { rspack } from '@rspack/core';

export default {
  plugins: [
    new rspack.experiments.VirtualModulesPlugin({
      'src/generated/config.js': 'export default { version: "1.0.0" };',
      'src/generated/constants.js': `
        export const API_URL = "${process.env.API_URL || 'http://localhost:3000'}";
        export const DEBUG = ${process.env.NODE_ENV !== 'production'};
      `,
    }),
  ],
};

Dynamic module creation

You can dynamically create or modify virtual modules using the writeModule method:

  • Type:
function writeModule(filePath: string, contents: string): void;
  • Parameters:

    • filePath: The virtual file path relative to compiler.context
    • contents: The content of the virtual file
  • Example:

rspack.config.mjs
import { rspack } from '@rspack/core';

const virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin();

export default {
  plugins: [
    virtualModulesPlugin,
    {
      apply(compiler) {
        compiler.hooks.beforeCompile.tap('MyPlugin', () => {
          // Dynamically create virtual modules
          const moduleContent = generateSomeContent();
          virtualModulesPlugin.writeModule('src/dynamic.js', moduleContent);
        });
      },
    },
  ],
};