Skip to content
Webpack Virtual Modules is a webpack plugin that lets you create, modify, and delete in-memory files in a way that webpack treats them as if they were physically presented in the file system.
Branch: master
Clone or download
Latest commit f172922 Oct 15, 2019

Webpack Virtual Modules

Build Status Twitter Follow

Webpack Virtual Modules is a plugin that allows for dynamical generation of in-memory virtual modules for JavaScript builds created with webpack. This plugin supports watch mode meaning any write to a virtual module is seen by webpack as if a real file stored on disk has changed.


Use NPM or Yarn to install Webpack Virtual Modules as a development dependency:

# with NPM
npm install webpack-virtual-modules --save-dev

# with Yarn
yarn add webpack-virtual-modules --dev


You can use Webpack Virtual Modules with webpack 3 and 4. The examples below show the usage with webpack 4 and its latest API for hooks. If you want to use our plugin with webpack 3, check out a dedicated doc:

Generating static virtual modules

Require the plugin in the webpack configuration file, then create and add virtual modules in the plugins array in the webpack configuration object:

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

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

module.exports = {
  // ...
  plugins: [

You can now import your virtual modules anywhere in the application and use them:

var moduleFoo = require('module-foo');
// You can now use moduleFoo

Generating dynamic virtual modules

You can generate virtual modules dynamically with Webpack Virtual Modules.

Here's an example of dynamic generation of a module. All you need to do is create new virtual modules using the plugin and add them to the plugins array. After that, you need to add a webpack hook. For using hooks, consult webpack compiler hook documentation.

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

// Create an empty set of virtual modules
const virtualModules = new VirtualModulesPlugin();

var compiler = webpack({
  // ...
  plugins: [

compiler.hooks.compilation.tap('MyPlugin', function(compilation) {
  virtualModules.writeModule('node_modules/module-foo.js', '');

In other module or a Webpack plugin, you can write to the module module-foo whatever you need. After this write, webpack will "see" that module-foo.js has changed and will restart compilation.

  'module.exports = { foo: "foo" };'

More Examples

API Reference


This project is inspired by virtual-module-webpack-plugin.


Copyright © 2017 SysGears INC. This source code is licensed under the MIT license.

You can’t perform that action at this time.