Rails Webpacker images not loading unless manually defined with import

≯℡__Kan透↙ 提交于 2020-01-15 10:31:28

问题


I'm working with @rails/webpacker 3 in a Rails 5.1 app. I've been trying to figure out if there is a way to not have to define importing every individual image in the respective pack/*.js files.

I have the default webpacker config setup and the image file saved at this location.

 <app_root>/app/javascript/images/image.png

In my view I have the image element set

#<app_root>/app/views/layouts/application.html.erb
...
<img src="<%asset_pack_path 'images/image.png%>"> 
...

The image will not load unless I import it in the pack files which I do here:

#<app_root>/app/javascript/packs/application.js
import 'images/image.png'

It seems like I'm doing additional unnecessary work to render the image in the application view. I'm assuming that asset_pack_path method and webpacker would be performing this image import since it seems like having to define it twice is duplicate code.

Am I missing something or is this the design intent on how to load images using webpack and rails?


回答1:


Looks like by adding this to my javascript worked out.

#<app_root>/app/javascript/application.js
const images = require.context('../images/', true)

Guidance was in an issue that I was directed to by others - https://github.com/rails/webpacker/issues/705




回答2:


UPDATE My original answer stopped working. Here is the currently working way. See also my comment at https://github.com/rails/webpacker/issues/705

add this to app/javascripot/packs/app.js (or any of your packs):

// Images
require.context('../images/static', true)

then use them in your Rails view like this, for example in app/views/layouts/application.html.erb:

<img src="<%= asset_pack_path 'media/user.jpg' %>" />

or

<%= image_pack_tag 'media/user.jpg %>

Note the media/ prefix, and dropping your original subfolder prefix.



来源:https://stackoverflow.com/questions/50701797/rails-webpacker-images-not-loading-unless-manually-defined-with-import

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