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

最后都变了- 提交于 2019-12-04 00:14:41

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.

For those who may still be having this issue, give this a try:

Put your img in app/assets/images. In this example my image is called 'logo.png'.

In your application.html.erb file, put this in the head:

<script type="text/javascript">
   window.logo = "<%= image_url('logo.png') %>"
</script>

Now in your component, render the image:

return (
  <div>
    <a href="/">
      <img src={window.logo}/>
    </a>
  </div>
);

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!