tooling.report

feature

URL

Can images be imported as asset URLs?

Person in shorts with blue hair walking left

Import an image and get a URL that can be used in an <img />.

Introduction

Images can be quite large depending on their format, quality and dimensions. For the majority of images that are too large to be inlined into JavaScript bundles, the most direct way to reference them from JavaScript is by their URL. Like most other non-JavaScript resources, images imported into the JavaScript module graph have the benefit of being treated as dependencies that can be processed and have their URLs hashed for effective long-term caching.

The Test

This test bundles a simple JavaScript module that imports an image file. Each build tool is configured to handle image imports by providing the image's generated asset URL as the result of the import statement.

index.js

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

image.png

<binary data>

After bundling is complete, the result should be a bundled version of index.js in which imagePath now refers to the generated hashed URL for image.png, also be present in the output directory.

Conclusion

browserify

(This test uses Browserify) urify-emitter plugin emits file into a specified directory and replaces file loading call with name of the emitted file.

parcel

Parcel supports importing raw assets to obtain their hashed URLs out-of-the box via the URL constructor.

rollup

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

webpack

Webpack's "asset/resource" module type allows referencing any file via new URL. This adds the referenced asset to the dependency graph and emits it to disk, replacing new URL references with the corresponding generated asset URLs.