webpack-virtual-modules

raw JSON →
0.6.2 verified Sat Apr 25 auth: no javascript

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.

error Error: Cannot find module 'virtual-module'
cause Virtual module path not resolved correctly by webpack
fix
Ensure the virtual module path is an absolute path or starts with './' or '../' relative to project root. Use path.resolve() to construct absolute paths.
error TypeError: VirtualModulesPlugin is not a constructor
cause Wrong import style: using destructuring when the export is default
fix
Use const VirtualModulesPlugin = require('webpack-virtual-modules'); or import VirtualModulesPlugin from 'webpack-virtual-modules';
error Error: webpack-virtual-modules: you must provide a virtual modules map to the constructor
cause Calling constructor without arguments when using the new API
fix
Pass an object as the first argument: new VirtualModulesPlugin({ './src/foo.js': '...' })
deprecated Old API: writeModule() and deleteModule() methods are deprecated in favor of constructor-based module definitions.
fix Pass an object to the constructor: new VirtualModulesPlugin({ 'path': 'content' }).
gotcha Virtual modules must have paths that resolve to valid module identifiers (e.g., absolute paths or relative to node_modules).
fix Use paths like 'node_modules/my-module.js' or absolute paths.
breaking Webpack 5 compatibility: fs access method changed. Older versions of this plugin may not work with webpack 5.
fix Update to v0.11.0 or later which supports webpack 5.
deprecated The `writeModule` method is deprecated as of v0.9.0.
fix Use constructor options or call `virtualModules.writeModule()` only if necessary.
gotcha Dynamic module content updates: Modifying virtual modules after compilation requires calling `invalidate()` on the plugin.
fix Call `virtualModules.invalidate()` after updating content using `writeModule()`.
npm install webpack-virtual-modules
yarn add webpack-virtual-modules
pnpm add webpack-virtual-modules

Basic setup with webpack to create a virtual module available as a dependency.

const VirtualModulesPlugin = require('webpack-virtual-modules');

const virtualModules = new VirtualModulesPlugin({
  'node_modules/virtual-module.js': 'module.exports = { foo: "bar" };',
});

module.exports = {
  // ... other config
  plugins: [
    virtualModules,
    // other plugins
  ],
};