在开发过程中,我(在运行bundle exec rails webpacker:install:erb
之后(在使用Webpack:的Rails6中使用此代码没有问题
# 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加载静态资产,因此没有任何链轮(尽管我没有删除它的宝石或触摸任何与资产管道相关的配置;只是暂时忽略它(。这意味着我将所有图像存储在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拒绝,因为找不到引用的.pngs(star-on-png和star-off.png(,因为(我认为(Webpack将它们编译到/public
目录中,所以它们不再存在于/media/images
路径中。不幸的是,Heroku上的指南没有涵盖Rails6/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
引用图像。你可能很想这样做,但是,如果只是为了这个小例子,那就没有必要了。