DEV Community

frustigor
frustigor

Posted on

How to inject DLL scripts into html with HtmlWebpackPlugin?

As a way to speed up building of webpack, DLL is an almost mentioned way. But when we use HtmlWebpackPlugin to auto inject scripts into html, the dll scripts will not be injected. So, do we have a way to do this?

Yes!

HtmlWebpackPlugin has hooks which can help us to implement this. In my solution, I create a shared plugin called InjectDllHtmlWebpackPlugin, and the source code:

class InjectDllHtmlWebpackPlugin {
  constructor(options) {
    this.options = options
  }
  apply(compiler) {
    compiler.hooks.compilation.tap('InjectDllHtmlWebpackPlugin', (compilation) => {
      compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync(
        'InjectDllHtmlWebpackPlugin',
        (data, cb) => {
          data.assets.js.unshift(...this.options.files)
          cb(null, data)
        }
      )
    })
  }
}

I used webpack v4.x, and HtmlWebpackPlugin version 3.2.0 whose hooks may change in version 4.x which is now in beta.

Let's look into HtmlWebpackPlugin's source code here. The author add some hooks for webpack v4, so that we can use htmlWebpackPluginBeforeHtmlGeneration hook to change assets.js option for the plugin to generate scripts tags.

Next, we use the previous plugin in webpack together with HtmlWebpackPlugin:

{
  plugins: [
    new DllReferencePlugin(...),
    new HtmlWebpackPlugin(...),
    // InjectDllHtmlWebpackPlugin should must come after HtmlWebpackPlugin
    new InjectDllHtmlWebpackPlugin({
      files: [
        'react.dll.js', // notice, this is the src url of script tag
      ],
    })
  ],
}

This is the way to auto add your dll scripts into your html. You can get my source code from project nautil.

Top comments (0)