Rails 7 上的 scss 文件中的 url() 错误
我在使用 Rails 7 项目中的 url()
css 函数时遇到问题。我在一个全新的版本上复制了它: https://github.com/paul-mesnilgrente /rails-7-url,请参阅此提交:https://github.com/paul-mesnilgrente/rails-7-url/commit/77e1379cd98827f43b02605852220cd3db93ce06
它使用 sass (参见 package.json) 以及 cssbundling-rails 和 sprockets-rails。如果您查看app/assets/stylesheets/application.sass.scss
,我有:background-image: url('images/background.jpg')
。 background.jpg
文件是 app/assets/images/background.jpg
。
我尝试了几种路径来包含该背景(../images/background.jpg
、/images/background.jpg
等),但没有任何效果。开发环境中的编译结果应该附加一个摘要哈希,但没有任何内容,并且路径仅转换为 /images/background.jpg
,这给出了 404。这让我觉得 sprockets 没有找不到背景图像,因此它不会“编译”该路径。
对我做错了什么有什么想法吗?
I'm having troubles with the url()
css function in my rails 7 project. I reproduced it on a brand new one: https://github.com/paul-mesnilgrente/rails-7-url, see this commit: https://github.com/paul-mesnilgrente/rails-7-url/commit/77e1379cd98827f43b02605852220cd3db93ce06
It uses sass (see package.json) with cssbundling-rails and sprockets-rails. If you look at the app/assets/stylesheets/application.sass.scss
, I have: background-image: url('images/background.jpg')
. And the background.jpg
file is app/assets/images/background.jpg
.
I tried several paths to include that background (../images/background.jpg
, /images/background.jpg
etc.) but nothing works. The compiled result in the development environment should have a digest hash appended to it but there's nothing and the path is only translated to /images/background.jpg
which gives a 404. This makes me thing that sprockets doesn't find the background image so it doesn't "compile" that path.
Any ideas of what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现这个问题实际上很愚蠢。在manifest.js中,我们默认有这一行
//= link_tree ../images
。问题是,rails 不会查找相对于样式表甚至相对于
app/assets
的资源。它仅相对于那些//= link_tree ...
路径。所以我之前没有尝试过的正确路径是 url("background.jpg") 。
旁注:如果您使用包含相对路径的数据表等库,则需要在manifest.js中添加一些链接
//= link_tree ../../../node_modules /datatables.net-zf/css
I found the problem which was actually pretty dumb. In manifest.js we have this line by default
//= link_tree ../images
.And the thing is, rails doesn't look for the assets relatively to your stylesheet or even relatively to
app/assets
. It's only relative to those//= link_tree ...
paths.So the right path, which I hadn't tried before was
url("background.jpg")
.Side note : If you use libraries like datatables which are including relative paths, you need to add something link this in manifest.js
//= link_tree ../../../node_modules/datatables.net-zf/css