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

标签 javascript ruby-on-rails webpack dev-to-production

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

# 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');
    }
  });
});

请记住,我也在使用 Webpack 来加载静态 Assets ,所以没有任何链轮(尽管我没有删除它的 gems 或触及与 Assets 管道相关的任何配置;只是暂时忽略它)。 这意味着我将所有图像存储在 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)

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

如有任何建议,我们将不胜感激!

最佳答案

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

app/
  javascript/
    images/
      star-on.png
      star-off.png
    packs/
      application.js
    raty.js

这就是您在 raty.js 中要做的:

import $ from 'jquery'
import 'raty-js'

import starOn from "./images/star-on.png"
import starOff from "./images/star-off.png"

$(document).on("turbolinks:load", () => {
  $('.star-rating').raty({
    readOnly: true,
    starOn: starOn,
    starOff: starOff,
    score() {
      return $(this).attr('data-score');
    }
  });
});

请注意,这里不需要使用 ERB;如果您有正确的导入路径,默认的 Webpacker 配置将知道如何解析图像的输出路径。

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

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

如果您想在 HTML 模板中通过 image_pack_tag 引用图像。您可能非常想这样做,但是,如果只是为了这个小示例,则没有必要。

关于javascript - Rails 6/Webpack 无法编译生产中从 js.erb 引用的图像? (但正在开发中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713944/

相关文章:

webpack - 如何编写基于其他模块动态添加模块到包中的 Webpack 插件?

javascript - 为什么我的 CSS 选择器无效?

javascript - 如何在函数中使用 $(this) ?

ruby-on-rails - 通过 Axlsx 添加到电子表格时正确设置 Excel 列宽

ruby-on-rails - 如何在没有 RVM 的情况下在 Ubuntu 上安装 Ruby 1.9.3?

node.js - Webpack 没有将 ES6 转换为 ES5

node.js - 调试 'serverless-webpack' : GraphQL error: Lambda services-publishService threw an Error during invocation

javascript - 为什么没有在这个函数中定义 "sprite"?

javascript - 使用Javascript文件(Google Analytics/Amazon Webstore)修改嵌入式Javascript

ruby-on-rails - Ruby On Rails - 无法通过报复在 has_many 中执行 where 语句