ruby-on-railssprocketsruby-on-rails-7

Bug on url() in scss files on rails 7


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?


Solution

  • 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