1

是否可以使用 html-webpack-plugin 在头部写入一些块,在正文中写入一些块?

这是我对 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']
};

当我在此配置中使用副本但更改了块时:

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 仅适用于 html-webpack-plugin 的最后一个块。

4

1 回答 1

0

您可以尝试分叉项目,然后摆弄如下代码:
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') {
   ...
 }

然后headScripts在您的插件定义中添加一个选项:

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
    })
  ]
于 2018-02-14T22:34:26.600 回答