Webpack 的 HtmlWebpackPlugin 如何控制某个 chunks 的 inject 位置?

https://segmentfault.com/q/1010000006591131

 

通过修改 HtmlWebpackPlugin 源码实现了

 

修改后的配置:

new HtmlWebpackPlugin({
  filename: 'index.html',
  template: './src/index.jade',
  inject: {
    head: ['chunks2'],
    body: ['chunks1', 'chunks3', 'vendor']
  },
  chunks: ['chunks1', 'chunks2', 'chunks3', 'vendor']
})

插件修改部分:

// ...

// 如果 inject 传入参数为对象则区分打包.
if (typeof this.options.inject === 'object') {
  this.options.inject.head.forEach(value => {
    var injectScripts = scripts.filter(script => script.attributes.src.indexOf(value) > -1)
    head = head.concat(injectScripts)
  })

  this.options.inject.body.forEach(value => {
    var injectScripts = scripts.filter(script => script.attributes.src.indexOf(value) > -1)
    body = body.concat(injectScripts)
  })
} else {
  // 原版逻辑.
  if (this.options.inject === 'head') {
    head = head.concat(scripts);
  } else {
    body = body.concat(scripts);
  }
}

// ...

 修改前:

 

修改后:

 

 效果图:

 

posted @ 2017-02-17 17:02  贝尔塔猫  阅读(4368)  评论(0编辑  收藏  举报