tooling.report

feature

URL

Import a binary file as an asset URL

Person in shorts with blue hair walking left

Introduction

Binary files are often large, and representing them as text can be inefficient. When an application imports a large binary file, it often makes more sense to load that data from a URL rather than inlining it into the JavaScript bundle.

The Test

This test bundles a JavaScript module that imports a large binary file, expecting the result of the import to be a URL. That URL should be usable for loading the binary data using fetch(url) or some other method.

index.js

import binURL from './binary.bin';
fetch(binURL).then(async r => {
  console.log(await r.arraybuffer());
});

Bundlers may use something other than a static import to achieve this. The test passes as long as the resulting URL can be stored in a variable.

binary.bin

<binary data>

The built result should be a copy of binary.bin with a hashed URL, and a JavaScript bundle that passes the hashed URL of binary.bin to fetch().

Conclusion

browserify

The Browserify plugin urify-emitter allows you to bring files into the build and returns the URL of the emitted file.

parcel

Parcel supports this out-of-the box via the URL constructor.

Issues

rollup

Plugin authors can use Rollup's emitFile method to add assets into the graph and return a URL to the asset.

webpack

Webpack supports referencing assets by default using new URL('./asset-path.abc', import.meta.url).