7

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.

jennas
  • 2,444
  • 2
  • 25
  • 31
  • 1
    One idea would be to do `var myDate = require('./path/to/dynamically/generated/file');` then, at build time, you would create a file at that path using whatever means you wanted. Does that help at all? – jamesplease Oct 21 '16 at 05:35
  • @jmeas Yeah i did think of that too.. I wanted to avoid doing that because I'm adding cruft files into peoples file systems whom use my plugin. Also it has a long 'require' path to a physical file. Where i want more of an alias type thing. – jennas Oct 21 '16 at 05:39
  • 2
    You could also write a webpack loader plugin that generates the js, and passes it on to the webpack compile process. – Chris Seufert Dec 07 '16 at 23:18
  • 2
    @ChrisSeufert do you have an example? Or docs? I did look into this but was all so confusing. – jennas Dec 08 '16 at 02:35

1 Answers1

7

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.

Roman M. Koss
  • 970
  • 1
  • 15
  • 33