rails/sprockets-rails

Bug on url() in stylesheets

paul-mesnilgrente opened this issue · 6 comments

I created a simple repository https://github.com/paul-mesnilgrente/rails-7-url to reproduce my problem. The only interesting part is in application.sass.scss: background-image: url('images/background.jpg'). The file is app/assets/images/background.jpg.

I tried a few variants of this path: /images/background.jpg, ../images/background.jpg, ./images/background.jpg but nothing works. The translated URL in the browser will always give a 404.

I saw a few PRs (#489, #476) around this lately but I didn't find how to fix my problem still.

It feels very strange that it doesn't work on a fresh rails project and nobody complained about it so I must miss something simple...

You can also note that if I include @import 'datatables.net-zf/css/dataTables.foundation.min', the images path are not translated either. I can include a commit with that if needed.

If you look at the CSS debugger of the browser you'll see that the background-image doesn't have any hash digest as it should.

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").

Now an issue remains for libraries. I have datatables.net-zf in my node_modules. I tried doing this in manifest.js: //= link_tree ../../../node_modules/datatables.net-zf/css because there's url(../images/sort_asc.png) in the css file I include. But this doesn't work because the image isn't found by sprockets.

@paul-mesnilgrente, did you ever get anywhere with this? I'm having a similar problem with jstree. It defines background-images relative to the CSS file. The images are in the same directory as the CSS file but sprockets won't find the images even when I link them directly. The only way I've been able to make it work is to copy the images to /assets/images which defeats the point of being able to draw from node_modules.

I think I have the same information in here: https://stackoverflow.com/questions/71423330/bug-on-url-in-scss-files-on-rails-7/71423760?noredirect=1#comment137148760_71423760

But I wrote:

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

If this can help you :)