Wrap Webpack chunks

2022-05-01

What and why?

Sometimes I would like to wrap webpack chunks (JavaScript code generated by webpack) before minification.

One such use case to help reduce code size. For example, if my project contains many JavaScript source files that call setTimeout, I would like the minifier to shorten it to one letter. (By default this won’t happen, because setTimeout is a global function.)

I could, of course, assign setTimeout to a variable, but use that variable whenever I need the function. However, this is undesirable because it changes the way the code is written.

A better solution is being able to “wrap” the code, after chunk generation by webpack but before minification.

{
  const {setTimeout} = globalThis;
  // original webpack chunk here
}

But how?

Webpack has a plugin called banner-plugin. Its intended use is to prepend or append author and/or copyright information (the “banner”), but we can use it in creative ways.

plugins: [
  new webpack.BannerPlugin({
    banner: '{ const {setTimeout} = globalThis;',
    raw: true,
  }),
  new webpack.BannerPlugin({
    banner: '}',
    raw: true,
    footer: true,
  }),
]

Alternatives?

There exists a plugin wrapper-webpack-plugin. I tried it, but decided it’s unusable, because —

1) The plugin has long not been maintained – its owner never responded to a pull request adding support for webpack 5.

2) The more serious problem is that it doesn’t support source maps.