tooling.report

feature

Data URL

Can images be imported as data URLs?

Person in shorts with blue hair walking left

Introduction

The smallest valid PNG image is 67 bytes. While such an image is unlikely to be used in an application, there are real cases where images are small enough that fetching them in a separate HTTP request would be wasteful. In cases where images are trivially small, or where an image is critical for the rendering of an application, it can be necessary to embed the image into JavaScript as a data URL.

Data URLs are a URLs that containing the mime type and data for a resource, typically encoded as Base64. The 67b PNG image above can be represented as the following 92b Data URL:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==

The Test

This test bundles a JavaScript module that imports an image. Each build tool is configured to encode images as Data URLs.

index.js

import imagePath from './image.png';
console.log(imagePath);

image.png

<binary data>

The result of building index.js should be a corresponding JavaScript bundle that includes an inlined copy of image.png as a Data URL.

Conclusion

browserify

(This test uses Browserify) urify transform privides ability to get data uri for the given file path.

parcel

Parcel supports this out-of-the box via an import with a special scheme, data-url:.

This only works with JavaScript imports. If you try and use it in HTML: <img src="data-url:./img.png">, the src is replaced with an internal identifier. However, this isn't required to pass the test.

Issues

rollup

Plugin authors can generate modules from any import statement. This example generates a data URL.

webpack

Webpack's url-loader allows importing a file into bundles, where the result of the import is a Base64-encoded Data URL as a String.