Importing images with Webpacker

Webpacker is Rails default solution for managing JavaScript modules within the application. Not everyone knows it but it can also be used for other assets like CSS, static files (i.e. images), or fonts, and completely substitute Sprockets on the field.

Importing CSS

To import CSS / SCSS file, just import the stylesheet file like a normal Javascript module (for SCSS make sure you have sass-loader, and sass packages installed) to your application.js pack:

import "../../stylesheets/application.scss"

Then add stylesheet pack to the template:

<!-- app/layouts/application.html.erb -->
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

Importing static files

Static files can be imported the same way as stylesheets (Webpacker supports libraries from node_modules directory out of the box - here I’m using icons from tabler-icons. package):

import "@tabler/icons/icons/trash.svg"
import "../../images/logo.png"

If you want to import all files from images directory, use require.context with useSubdirectories parameter set to true:

require.context('../../images', true)

Then, use image_pack_tag helper (remember to prefix paths with media directory) to add <img> tag to the template:

<%= image_pack_tag 'media/images/logo.png' %>
<%= image_pack_tag 'media/icons/trash.svg' %>

To import images into the stylesheet, use regular url expression (with ~ prefix for files coming from node_modules folder):

.logo {
  background: url("../images/logo.png")

.icon {
  background-image: url('[email protected]/icons/icons/trash.svg')

Importing SVG images

To display SVG files inline (i.e. to modify their styles via CSS), install inline_svg gem, and use inline_svg_pack_tag helper (media/ prefix is also needed) to add <svg> tag to the template:

<%= inline_svg_pack_tag 'media/icons/trash.svg' %>

Additional resources

For more advanced Webpacker topics, Ross Kaffenberger’s blog is great place to start diving down the rabbit hole ;) .