> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# VirtualModulesPlugin


[Added in v1.5.0](https://github.com/web-infra-dev/rspack/releases/tag/v1.5.0)Rspack 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](https://github.com/sysgears/webpack-virtual-modules), deeply integrated with Rspack to provide equivalent functionality with better performance.

## Examples

### Basic usage

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

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

new rspack.experiments.VirtualModulesPlugin({
  // ...modules
});
```

```js title="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.

:::note
Because the plugin's virtual modules are managed on the Rust side,
the `writeModule` method becomes available only after the Rust compiler has been initialized.
For example, invoking `writeModule` within the `beforeCompile` or `compile` hooks
will throw the following error: `Error: Virtual file store has not been initialized.`
:::

- **Type:**

```ts
function writeModule(filePath: string, contents: string): void;
```

- **Parameters:**
  - `filePath`: The virtual file path relative to [compiler.context](/api/javascript-api/compiler.md#context)
  - `contents`: The content of the virtual file

- **Example:**

```js title="rspack.config.mjs"
import { rspack } from '@rspack/core';

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

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

## Options

- **Type:** `Record<string, string>`
- **Default:** `{}`

The optional constructor argument maps each virtual file path to its contents. Paths are resolved relative to [compiler.context](/api/javascript-api/compiler.md#context).
