Search code examples
javascriptwebpackwebpack-2webpack-plugin

How to dynamically add a module/dependency with a webpack plugin?


I feel like what i'm trying to achieve isn't that hard.. but the webpack docs are in a serious disarray and I'm burning many hours on this.

How do i inject a "dynamic" module into a webpack build? I want to create this module at build time.

For a simple example how do i inject this string as a new module at build?

"module.exports = new Date();"

Then lets say I want that module to have the name "myDate"

I would very much like any other module in my application to be able to resolve it with:

var myDate = require('myDate');

Now this is a very simple example. My purpose will be much more complex and involve reading files to create this "dynamic" module. I'm aware of the define plugin and it unfortunately does not suit my needs.

I would greatly appreciate any help. Thanks.


Solution

  • Found this plugin: virtual-module-webpack-plugin

    Usage example described in README.md

    const VirtualModulePlugin = require('./virtual-module-webpack-plugin');
    
      // ...
    
      plugins: [
        new VirtualModulePlugin({
          moduleName: 'src/mysettings.json',
          contents: JSON.stringify({ greeting: 'Hello!' })
        })
      ]
    }
    

    You can review implementation and try your own.