Webpack plugin that allows you to create virtual (in-memory) modules at compile time. Current stable version 0.6.2. Updated sporadically; last release Nov 2023. Key differentiator: enables injecting custom modules that don't exist on disk, useful for runtime-generated code or mocking, without modifying the filesystem. Supports webpack 4 & 5. Alternatives like virtual-module-webpack-plugin or inline-source-map have different APIs or less maintenance.
npm install webpack-virtual-modulesVerified import paths — ran on the pinned version, not inferred.
Basic setup with webpack to create a virtual module available as a dependency.
Pass an object to the constructor: new VirtualModulesPlugin({ 'path': 'content' }).Use paths like 'node_modules/my-module.js' or absolute paths.
Update to v0.11.0 or later which supports webpack 5.
Use constructor options or call `virtualModules.writeModule()` only if necessary.
Call `virtualModules.invalidate()` after updating content using `writeModule()`.
Ensure the virtual module path is an absolute path or starts with './' or '../' relative to project root. Use path.resolve() to construct absolute paths.
Use `const VirtualModulesPlugin = require('webpack-virtual-modules');` or `import VirtualModulesPlugin from 'webpack-virtual-modules';`Pass an object as the first argument: `new VirtualModulesPlugin({ './src/foo.js': '...' })`