Site is under renovation and you may experience weirdness.

Webpacker 6: Image Asset Guide

Andrew Mason

Andrew Mason

Updated Feb 16th, 2021


In order to use your images and SVG files with Webpacker 6, you need to put them in the correct place and import them into your context.

Install

We should be good here.

Usage

Add Assets

mkdir -p app/javascript/media/images

Require Context

// app/javascript/packs/application.js
+
+ function importAll(r) {
+  r.keys().forEach(r);
+ }
+ // Add relevant file extensions as needed below.
+ // I'm sure there is a better way :shrug:
+ importAll(require.context('../media/images/', true, /\.(svg|jpg)$/));

Verify

Note: Restart the dev server for good luck!

Add an SVG and PNG into app/javascript/media/images

In one of your views, add two image tags:

<img src="<%= asset_pack_path 'media/images/icon.svg' %>" />
<img src="<%= asset_pack_path 'media/images/surf.jpg' %>" />

Reload your browser and you should see your images.

Note that <%= asset_pack_path 'media/images/icon.svg' %> only returns a string, so if you would rather inline your SVG files you will need to refer to the Webpack Asset Modules documentation and merge your changes into your Webpack context, as explained in these Webpacker docs.


Series
webpacker-6

Discuss
on Twitter↗
Updated On
Feb 16th, 2021
Published On
Dec 24th, 2020
Word Count
213 words
Reading Time
1 min read