除非使用导入手动定义,否则不会加载Rails Webpacker映像 [英] Rails Webpacker images not loading unless manually defined with import
问题描述
我正在Rails 5.1应用程序中使用@ rails/webpacker 3.我一直在尝试找出是否有一种方法不必定义在相应的pack/*.js文件中导入每个单独的图像.
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.
我有默认的webpacker配置设置,并且图像文件保存在此位置.
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'
似乎我正在做其他不必要的工作来在应用程序视图中渲染图像.我假设asset_pack_path方法和webpacker将执行此图像导入,因为似乎必须两次定义它是重复代码.
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.
我是否缺少某些东西?或者这是设计目的,目的是如何使用Webpack和Rails加载图像?
Am I missing something or is this the design intent on how to load images using webpack and rails?
推荐答案
更新我原来的回答停止了工作.这是当前的工作方式.另请参见 https://github.com/rails/webpacker/issues/705 a>
UPDATE My original answer stopped working. Here is the currently working way. See also my comment at https://github.com/rails/webpacker/issues/705
将此添加到app/javascripot/packs/app.js
(或您的任何包装)中:
add this to app/javascripot/packs/app.js
(or any of your packs):
// Images
require.context('../images/static', true)
然后在这样的Rails视图中使用它们,例如在app/views/layouts/application.html.erb
中:
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' %>" />
或
<%= image_pack_tag 'media/user.jpg %>
注意media/
前缀,并删除原始的子文件夹前缀.
Note the media/
prefix, and dropping your original subfolder prefix.
这篇关于除非使用导入手动定义,否则不会加载Rails Webpacker映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!