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.
When creating a VirtualModulesPlugin instance, you can directly configure virtual modules in the constructor:
import { rspack } from '@rspack/core';
new rspack.experiments.VirtualModulesPlugin({
// ...modules
});modules (optional): An object where keys are file paths and values are file contents.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'};
`,
}),
],
};You can dynamically create or modify virtual modules using the writeModule method.
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.
function writeModule(filePath: string, contents: string): void;Parameters:
filePath: The virtual file path relative to compiler.contextcontents: The content of the virtual fileExample:
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);
});
},
},
],
};