Rails 6/Webpack 无法编译生产中从 js.erb 引用的图像?(但正在开发中)

Dij*_*e85 3 javascript ruby-on-rails dev-to-production webpack

在开发过程中,我bundle exec rails webpacker:install:erb在 Rails 6 中使用 Webpack 运行此代码没有任何问题(运行后):

# app/javascript/raty.js.erb

<% helpers = ActionController::Base.helpers %>

$(document).on("turbolinks:load", () => {
  $('.star-rating').raty({
    starOn: "<%= helpers.asset_pack_path('media/images/star-on.png') %>",
    starOff: "<%= helpers.asset_pack_path('media/images/star-off.png') %>",
    readOnly: true,
    score: function () {
    return $(this).attr('data-score');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

请记住,我也使用 Webpack 来加载静态资产,因此没有任何链轮(尽管我没有删除它的 gems 或触及与资产管道相关的任何配置;只是暂时忽略它)。这意味着我将所有图像存储在 中app/javascript/images,然后根据文档要求:

# app/javascript/packs/application.js

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
const images = require.context('../images', true)
const imagePath = (name) => images(name, true)
Run Code Online (Sandbox Code Playgroud)

然而,在生产中,我的推送被 Heroku 拒绝,因为找不到引用的 .png(star-on.png 和 star-off.png),因为(我认为)Webpack 将它们编译到目录中/public,所以它们是路径中不再存在/media/images。不幸的是,Heroku 上的指南不涵盖 Rails 6/Webpack,而且我遇到的所有答案都是针对 Sprockets,而不是 Webpack。

任何建议将非常感激!

ros*_*sta 5

在 Webpack 领域,您也可以“导入”图像。给定以下目录结构:

app/
  javascript/
    images/
      star-on.png
      star-off.png
    packs/
      application.js
    raty.js
Run Code Online (Sandbox Code Playgroud)

这就是您将在以下位置执行的操作raty.js

app/
  javascript/
    images/
      star-on.png
      star-off.png
    packs/
      application.js
    raty.js
Run Code Online (Sandbox Code Playgroud)

请注意,此处无需使用 ERB;假设您有正确的导入路径,默认的 Webpacker 配置将知道如何解析图像的输出路径。

另外,您只需要以下内容:

const images = require.context('../images', true)
// ...
Run Code Online (Sandbox Code Playgroud)

如果您想通过image_pack_tagHTML 模板中的参考图像。您可能很想这样做,但是,如果只是为了这个小例子,则没有必要。