26

I am using Webpacker with rails 5.1.4 to play with React, Redux, and react-router-dom.

I have a Navbar.jsx component in app/javascript/src/components/ that needs to display an image, but I am not able to access my images stored in app/assets/images/.

Here is what I've tried :

<img src="logo.png" alt="Logo" />
<img src="assets/logo.png" alt="Logo" />
<img src="assets/images/logo.png" alt="Logo" />

From root path the last attempt works because /assets/images/logo.png does exist, but when I navigate to /posts/:id, it gives me the following error:

logo.png:1 GET http://localhost:3000/posts/assets/images/logo.png 404 (Not Found)

Can you help me? And more over what's your way to handle images in that kind or hybrid React/Rails app?

Thanks

4

5 回答 5

38

只需编辑文件config/webpacker.yml并替换此行:

resolved_paths: []

有了这个:

resolved_paths: ['app/assets']

然后,将图像放入app/assets/images文件夹并像这样加载它:

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

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

export default MyComponent
于 2017-10-30T07:57:34.067 回答
4
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

您甚至可以在组件中创建图像文件夹。将其加载到组件文件中,如下所示 -

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 将这些图像路径转换为包。

于 2019-04-11T13:38:36.143 回答
2

2021 年更新(rails 6.1.4),resolved_paths密钥已更改为additional_paths.

所以,改变:

# config/webpacker.yml

default: &default
  resolved_paths: []

进入:

# config/webpacker.yml

default: &default
  additional_paths: ['app/assets']

其余的都在丹尼尔的回答之后

于 2021-08-23T08:49:16.527 回答
0

也许这会有所帮助: https : //engineering.klarna.com/migrating-from-rails-asset-pipeline-to-node-s-webpack-684230e3a93a 看看图像部分。

于 2017-10-20T08:00:41.670 回答
-1

对于那些可能仍然遇到此问题的人,请尝试一下:

将你的 img 放在 app/assets/images 中。在此示例中,我的图像称为“logo.png”。

在您的 application.html.erb 文件中,将其放在头部:

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

现在在您的组件中,渲染图像:

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

希望这可以帮助。

于 2019-07-30T01:38:46.123 回答