Using Rails assets in Webpacker

Eleni Chappen
20spokes Whiteboard
1 min readOct 20, 2017

In hybrid Rails/React projects, assets often need to be shared between the Rails asset pipeline and your Javascript environment. If you’re using the Webpacker gem, here’s how to include Rails asset paths in your bundle:

The Webpacker docs tell you to add any desired Rails asset paths to resolved paths in config/webpacker.yml:

resolved_paths: ['app/assets/images']

This path can be as specific as you need it to be, like app/assets/images or app/assets/stylesheets. In fact, you should narrow them down as much as possible to keep your build time short.

Once this path is recognized by Webpacker, you can import image paths in a few ways:

The first way is to import a single file:

import myImage from '../my_image.png'

Then use it in a React image tag like so:

render <img src={myImage} />

If you need to import lots of images and don’t want to write a separate import statement for each one, you could use require.context to create a helper method:

const icons = require.context('../icons', true)
export const iconPath = (name) => icons(name, true)

Then import your helper and use it in your React component:

import { iconPath } from './helpers/iconPath' // or whatever your path is...render <img src={iconPath('my_image.png')} />

Boom! h/t to all the contributors to this issue thread for this nifty helper method.

--

--