2

I'm writing a webpack Plugin and Loader and I'd like to create a "dynamic" module that's generated through my Plugin.

Basically, I want my loader emit an import to the dynamic module, like this:

module.exports = function (content) {
  return `
    const dynamicModule = require('./the-dynamic-module')
    // module.exports = ...
`;
}

The Plugin should generate "./the-dynamic-module", and ideally, the loader should be re-built every time the dynamic module changes.

Is there a way to achieve this?

There's a Plugin that generates virtual modules, but they're static. I'd like to generate a dynamic one, during compilation time.

Any help is appreciated! Cheers.

Endel Dreyer
  • 1,644
  • 18
  • 27

1 Answers1

3

You can use the plugin below to generate virtual modules at compile time (I am the author of this plugin): https://github.com/sysgears/webpack-virtual-modules

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

var virtualModules = new VirtualModulesPlugin();

var compiler = webpack({
    // ...
    plugins: [
       virtualModules
    ]
});

compiler.watch();

Later in some other code, perhaps in your Webpack plugin you call:

virtualModules.writeModule('./the-dynamic-module.js', 
    'module.exports = ...the contents of dynamic module...');

Each time you write dynamic module via virtualModules.writeModule it will have the same effect as if it was a real file on the filesystem that was changed - the Webpack will restart the compilation and will trigger loaders configured to process this file type.

Viktor Vlasenko
  • 2,332
  • 14
  • 16
  • 2
    Is it possible to use this technique to emit virtual submodules truly dynamically (in a loader) based on the currently processed module contents? The case would be to extract a part of a module with extension .ext1 (processed by our custom loader) into a virtual module with extension .ext2 to be processed by the loader specified in config for .ext2), and then just require .ext2 from .ext1 to include the processed ext2-loader result. – Alexander Chudesnov Oct 24 '18 at 11:19
  • For anyone interested, yes this is possible, and how `astroturf` emits css files extracted from css template tags: https://github.com/4Catalyzer/astroturf – monastic-panic Sep 03 '19 at 13:19
  • but it uses deprecated loader api, "loaderContext.compilation" – ElSajko Oct 17 '19 at 15:49