Webpack在Rails 5.1.7中删除资产管道后找不到图像路径

时间:2020-07-02 14:58:31

标签: ruby-on-rails webpack ruby-on-rails-5 webpacker

我正在使用Rails 5.1.7。并尝试从资产管道迁移到Webpacker,我已经运行过rake asset:precompile

我收到此消息:

Webpacker can't find logo.png in /***/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
  "application.js": "/packs/js/application-a5be4c0a9f54fffa5cb7.js",
  "application.js.map": "/packs/js/application-a5be4c0a9f54fffa5cb7.js.map",
  "entrypoints": {
    "application": {
      "js": [
        "/packs/js/application-a5be4c0a9f54fffa5cb7.js"
      ],
      "js.map": [
        "/packs/js/application-a5be4c0a9f54fffa5cb7.js.map"
      ]
    }
  }
}

那是在将我的图像设置在app/javascript/images中并验证了logo.png的位置之后。

提示此问题的行是:

   <%= link_to asset_pack_path('logo.png', alt: 'logo', width: 150), locale_root_path, class: 'logo'%>

如果我只是删除该行,它将带我到该文件夹​​(app / javascript / image)中另一个图像的路径。

我有此摘录来配置我的app / javascript / packs / application.js文件中的图像路径为:


const images = require.context('../images', true)
const imagePath = (name) => images(name, true)


2 个答案:

答案 0 :(得分:1)

首先,您需要告诉webpack您要使用此图像文件,因此(例如)在您的app / javascript / packs / application.js文件中放置:

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

然后确认图像确实已编译到清单中。 然后将该图像放入链接中,尝试(我不太确定webpacker可以处理此问题)image_pack_tag('media/images/logo.png')

尝试一下,让我们知道会发生什么。

答案 1 :(得分:1)

Webpack需要配置为编译图像:

在您的app/javascript目录中,创建一个图像文件夹,并将logo.png放在其中。

现在,您的图像已使用Webpack编译,

image_tag已更改为image_pack_tag。但是,默认情况下,您每次必须传递整个映像路径,以media/开头,然后是webpacker.yml配置文件中定义的webpack源路径中的路径。例如:

<%= image_pack_tag 'media/images/logo.png', alt: 'logo', width: 150%>

要解决此问题,您可以使用require.context

在您的网页入口点中,默认情况下它位于app/javascript/packs/application.js中,您应该添加以下行:

const images = require.context("../images", true);

要访问视图中的徽标图像,现在可以使用:

<%= image_pack_tag 'logo.png', alt: 'logo', width: 150%>