tooling.report

feature

Brotli

Can bundles be pre-compressed with Brotli?

Person in shorts with blue hair walking left

Introduction

Compressing data sent to the browser is a prerequisite for good loading performance, and implementing compression seldom requires architectural changes. Gzip compression is fast enough that it can be applied to all HTTP responses, but other compression algorithms are capable of further size reduction.

Many hosting providers allow supplying pre-compressed versions of assets. Build tools can generate these compressed versions automatically and using better compression, since computation is done ahead-of-time that would be too slow to do per-request.

The Test

This test bundles three JavaScript modules, then generates Brotli-compressed versions of the resulting bundle(s) with a .br file extension appended.

index.js

import { logCaps } from './utils.js';
import { exclaim } from './exclaim.js';
logCaps(exclaim('This is index'));

utils.js

export function logCaps(msg) {
  console.log(msg.toUpperCase());
}

exclaim.js

export function exclaim(msg) {
  return msg + '!';
}

The result of the test should be one or two JavaScript bundles (depending on the build tool configuration), each with a corresponding Brotli-compressed *.br version. Ideally, it should be possible to specify the level of compression to apply.

Conclusion

browserify

This test uses gulp-brotli plugin which uses the native brotli support in node.js
You can change the input to compress other types of files or chan this into existing build proccess.

parcel

There is a plugin infrastructure for Parcel 2 that is probably capable of solving this, but at the time of writing, the documentation doesn’t really tell me how.

Issues

rollup

Rollup's generateBundle hook gives you full access to build details before files are written. You can add additional files at this point too.

webpack

CompressionWebpackPlugin or BrotliPlugin can both be used to generate brotli-compressed versions of output files at build time. Both plugins use Node's native brotli support when available, however CompressionWebpackPlugin exhibits better performance since it uses the asynchronous brotliCompress() interface.