tooling.report

feature

Array buffer

Import a binary file as an array buffer

Person in shorts with blue hair walking left

The Test

In cases where a small amount of arbitrary binary data needs to be available synchronously within a module, it can be advantageous to inline the data into the JavaScript bundle. This test bundles a module that imports a binary file, expecting an ArrayBuffer as the result of the import.

import buffer from 'import-binary-somehow';
console.log(buffer.byteLength);

The build result should be a single JavaScript bundle containing the binary, which should be encoded in an efficient text format like base64.

Conclusion

browserify

You can use browserify’s brfs to convert a binary to base64, then convert to Array Buffer using the base64-arraybuffer decoder.

parcel

This example uses a custom Parcel Transformer plugin to convert the binary file to Base64 and inline it into a JavaScript module along with a helper to decode it at runtime. The helper is in a separate file, so it is not duplicated and can be code split.

As an alternative implementation, one could use an Optimizer plugin instead, which would allow the file to be processed through the whole transforming, bundling, and optimizing phases before being inlined back into the original bundle. An example of that is in the documentation.

rollup

Rollup plugins are simple to write. In this case, a module was generated that exports the file as a base64 string, wrapped in a function that converts base64 to an array buffer. The function that does the conversion is in a virtual module, so it isn't duplicated, and can be code-split.

webpack

arraybuffer-loader is an off-the-shelf loader that encodes imported files as Base64, then exports the decoded contents as an ArrayBuffer. This can also be achieved by chaining together url-loader's base64 option and a quick base64-to-arraybuffer implementation. Since that's basically what arraybuffer-loader does, we'll use the one that was already built.