Webpack - html-webpack-plugin - one filename - multi inject

783 views Asked by At

Is it possible to use html-webpack-plugin to write some chunks in head and some in body?

This is my config for html-webpack-plugin:

var HtmlWebpackPluginConfigIndex = {
  template: path.join(__dirname, 'src/core/server/views', 'index.dust'),
  filename: 'core/server/views/index.dust',
  hash: true,
  chunksSortMode: 'none'
  // chunks: ['core/public/js/vendor']
};

When I use copy with this config but with changed chunks:

var HtmlWebpackPluginConfigIndex = {
  template: path.join(__dirname, 'src/core/server/views', 'index.dust'),
  filename: 'core/server/views/index.dust',
  hash: true,
  inject: 'head',
  chunksSortMode: 'none'
  chunks: ['core/public/js/vendor']
};


var HtmlWebpackPluginConfigIndex2 = {
  template: path.join(__dirname, 'src/core/server/views', 'index.dust'),
  filename: 'core/server/views/index.dust',
  hash: true,
  inject: 'body',
  chunksSortMode: 'none'
  chunks: ['core/public/js/app']
};

....

new HtmlWebpackPlugin(HtmlWebpackPluginConfigIndex);
new HtmlWebpackPlugin(HtmlWebpackPluginConfigIndex2);

Webpack apply only last of chunks for html-webpack-plugin.

1

There are 1 answers

0
WeezyKrush On

you could try forking the project, then fiddle the code something like this:
html-webpack-plugin index.js:

HtmlWebpackPlugin.prototype.generateAssetTags = function (assets) {
    ...
    // Add scripts to body or head
    //  <<< You would add this bit >>>
    if (!! this.options.headScripts) {
        var hScripts = this.options.headScripts;
        head = head.concat(scripts.filter((s) => {
          var src = s.attributes.src;
          return hScripts.indexOf(src) > -1;
        }));
        body = body.concat(scripts.filter((s) => {
          var src = s.attributes.src;
          return hScripts.indexOf(src) < 0;
        }));
    // <<< to here (and the following "else" in front of the if) >>>
    else if (this.options.inject === 'head') {
   ...
 }

and then add a headScripts option to your plugin definition:

plugins: [
    new HTMLWebpackPlugin({
      template: path.join(__dirname, 'src','core','server','views', 'index.dust'),
      filename: 'core/server/views/index.dust',
      headScripts: ['vendor.bundle.js'] // or whatever your output filename is
    })
  ]