Images in your Rails app with Webpacker

Modern web development is almost impossible without adding Javascript into the mix. Also Rails took the plunge by adding the Webpacker gem into the mix. This allows for really advanced user interfaces. It’s no secret we love this mix of technology, though we use Javascript in moderation (as we are small and bootstrappers).

Sjabloon relies heavily on Webpacker and by default we move all frontend code (Javascript, Stylesheet and images) into its separate “frontend” folder in the root of your application (instead of the Rails-default of “app/javascript”). This is configured in “config/webpacker.yml” and then under the source_path key.

But the downside is, if you blinked your eyes, some previous simple things, are different now. Adding images into your views can be such thing. It’s actually not much harder than the previously used image_path() helper.

First, assuming you use Sjabloon, store your images in “frontend/images” (or a sub-directory). Then in your view: image_pack_tag('media/images/some_image.jpg').

All images in this directory (and subsequent subdirectories) are loaded by these lines in the “frontend/packs/application.js”

const images = require.context('../images', true)
const imagePath = (name) => images(name, true)

And that’s it really. The problem most stumble upon is missing to prepend their path with “media” (which is necessary since Webpacker 4).

A Rails SaaS starter kit to build successful products

Get started

25+ developers, companies and freelancers bought Sjabloon in the last 4 weeks