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 />.


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.


import imagePath from './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.



(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 supports importing raw assets to obtain their hashed URLs out-of-the box via an import with a special scheme, url:.


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


Webpack's file-loader allows importing any file into the dependency graph, emitting it to disk with a configurable templated name. The result of the import is the final URL of the file as a String.