简体   繁体   中英

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.

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 require ing 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM