Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 706
jennas Avatar asked Oct 21 '16 05:10

jennas


People also ask

Does webpack bundle Node_modules?

Webpack allows you to define externals - modules that should not be bundled. When bundling with Webpack for the backend - you usually don't want to bundle its node_modules dependencies. This library creates an externals function that ignores node_modules when bundling in Webpack.

How do I include a JavaScript file in webpack?

You can use webpack-inject-plugin to inject any JS code as string into the resulting . js bundle created by webpack. This way you can read the File you want to inject as a string (e.g. fs. readFile in nodejs) and inject it with the plugin.

What's the difference between webpack loaders and plugins?

Loaders work at the individual file level during or before the bundle is generated. Plugins: Plugins work at bundle or chunk level and usually work at the end of the bundle generation process.


1 Answers

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.

like image 72
Roman M. Koss Avatar answered Oct 18 '22 00:10

Roman M. Koss