How to handle images in a Rails / Webpacker / React app? How to handle images in a Rails / Webpacker / React app? ruby-on-rails ruby-on-rails

How to handle images in a Rails / Webpacker / React app?


Just edit the file config/webpacker.yml and replace this line:

resolved_paths: []

with this this:

resolved_paths: ['app/assets']

Then, put the image in app/assets/images folder and load it like this:

import React from 'react'import MyImage from 'images/my_image.svg'const MyComponent = props => <img src={MyImage} />export default MyComponent


If we leave resolved_path as [] in webpacker.yml also it works.Example = # Additional paths webpack should lookup modules  # ['app/assets', 'engine/foo/app/assets']  resolved_paths: []  static_assets_extensions:    - .jpg    - .jpeg    - .png    - .gif    - .tiff    - .ico    - .svg    - .eot    - .otf    - .ttf    - .woff    - .woff2

You can even create an image folder in your components. Load it in the component file like below-

import React from 'react;import MyImage from '${imagePath}/example1.png'export class MyComponent extends React.Component {  render() {  return (  <React.Fragment>   <img src={MyImage} alt="Image text"/>  </React.Fragemnt>  ) }}

Webpacker converts these image paths to packs.


Update 2021 (rails 6.1.4), the resolved_paths key has changed into additional_paths.

So, change :

# config/webpacker.ymldefault: &default  additional_paths: []

into:

# config/webpacker.ymldefault: &default  additional_paths: ['app/assets']

and the rest following Daniel's answer's