React_on_rails: How to include images from asset pipeline in JS client?

Created on 19 Feb 2016  路  7Comments  路  Source: shakacode/react_on_rails

The problem

I'm currently using the asset pipeline to serve images from my rails server.

For example, let's say I have an image at:

rails-app/app/assets/images/sprint.jpg

In erb code, I'd use image_tag or something, and it would generate a fingerprinted link like this:

https://domain.com/assets/sprint-42eb38fb2cb471821a1435cab589e590.jpg

And if I tried to access the non fingerprinted asset in production, I'd get a 404:

https://domain.com/assets/sprint.jpg

What is the best way to deal with this if I want to include assets from my asset pipeline in my React code?

Tentative solution:

Run all of my JS files through erb. It seems a little ghetto to have .jsx.erb files and to have to run them through another cycle. Maybe it's the best solution. I could just make it so that my final generate bundle is ran once, and have all of the erb executed.

This would make my local dev a bit of a pain. I'd make an imageUrl function that creates an erb tag in prod, and a simple asset link in dev.

Please help!

How have other people been handling this? Any suggestions?

question

Most helpful comment

I think there's 2 options:

All 7 comments

Best thing I've come up with:

  1. Creating an assetPaths.js.erb file in /app/assets/javascript/assetPaths.js.erb
  2. Then I tell my asset pipeline to Rails.application.config.assets.precompile += %w( assetPaths.js )
  3. Include that in my master JS file for my client side app:
// The equivalent of application.js for the GO CUBES site

//= require assetPaths
//= require generated/vendor-bundle
//= require generated/app-bundle

And now I have a beautiful global dict of available asset paths.

This isn't great but it works. Would love to hear any other suggestions!

Actually this doesn't work with server side rendering, unfortunately.

I think there's 2 options:

@justin808 thanks! I think option 1 is best.

This might cause some caching issues with cloud front / cloudflare, but we'll solve that another day.

Appreciate the prompt response!

For anyone who stumbles on this ticket, #670 offers an updated solution.

How about if you put our image under app/javascripts/images and will reference it from your JS code with:

import React from 'react'
import MyImage from 'images/my_image.svg'

const MyComponent = props => <img src={MyImage} />

export default MyComponent

See this Stackoverflow answer for the details

In your Rails templates you can use image_pack_tag helper:

= image_pack_tag 'my_image.svg'
Was this page helpful?
0 / 5 - 0 ratings

Related issues

evolve2k picture evolve2k  路  4Comments

hakunin picture hakunin  路  3Comments

cubadomingo picture cubadomingo  路  6Comments

stereodenis picture stereodenis  路  9Comments

thomassnielsen picture thomassnielsen  路  4Comments