Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a file to a bundle in Webpack, or inject required code?

I'm trying to build a plugin that injects a module/file into the client bundle.

An entry config might look like:

entry: {
  'main': [
    'some-stuff'
  ],
}

And I want to use my plugin like:

function SomePlugin(options) {
    this.entryToAppendTo = options.entryToAppendTo
}

...

plugins: [
  new SomePlugin({ entryToAppendTo: 'main' })
]

In my plugin I want to require that file as if it were done in Webpack itself, something like:

SomePlugin.prototype.apply = function(compiler) {

    compiler.plugin( 'emit', function( compilation, callback ) {

        var additionalModule = 'my-module?some-stuff=' + Date.now();
        // how to add this to the specified entry?

    })

});

Note that I'm passing a dynamic query string, which is why i'm aiming to do this in a plugin.

I want to append a file to the bundle, or somehow inject it into the client bundle. I've tried adding it to compilation.assets as shown here but it doesn't go into the actual bundle. I've also tried adding a child compiler as demonstrated in this question but same problem.

like image 926
Andy Ray Avatar asked Jun 29 '16 22:06

Andy Ray


1 Answers

This sounds similar to what I was trying to do here (with limited success): Webpack plugin: how can I modify and re-parse a module after compilation?

The problem with just inserting a module into your bundle is that, even if you get it in there, a compiled module in webpack is a function that some other part of the bundled source supposedly calls -- so unless some other part of the bundled source code is requireing the bundle you inserted, it won't get executed.

Could you solve this with a custom loader that strategically inserts a require for the module you want to include?

like image 108
Brendan Gannon Avatar answered Oct 16 '22 21:10

Brendan Gannon