Description
Suppose this setup:
/* assets/styles/app.scss */
import 'tools/base';
/* assets/styles/tools/base.scss */
.splash {
background-image: url('../../images/login-bg.png');
}
The image lives at assets/images/login-bg.png
, so the relative path above is, correctly, relative to the source file. Currently, if you compile this, because the contents are all compiled into, basically, assets/styles/app.css
, the relative path will now be incorrect.
Fix
I have 2 ideas to fix this:
- rails-sass look like they have you use some special fake functions in your scss files - https://github.com/rails/sass-rails#asset-helpers (the code, I think, actually lives in https://github.com/sass/sassc-rails). I'm not entirely sure how the implementation is done, but it looks like you literally do
asset-path("rails.png")
in your CSS files and it's written.
Pros: looks simple to implement.
Cons: this is magic, and your editor won't like it.
- When the final
.css
file is built, we can also have it output an importmap (also, it would be great to expose that importmap - or perhaps "embed" it in the.css
file for simplicity if possible in dev mode). We can, in theory, use this importmap to do this logic:
A) Determine that the background-image: url('../../images/login-bg.png');
line came from assets/styles/tools/base.scss
B) Determine that this file lives one directory deeper than the source, assets/styles/app.scss
.
C) Adjust the path accordingly to ../images/login-bg.png'
This might be trickier to implement - I've never parsed a sourcemap for info - but would be a completely clean solution. This is also how resolve-url-loader
from Webpack works - https://github.com/bholloway/resolve-url-loader/blob/HEAD/packages/resolve-url-loader/docs/how-it-works.md#the-solution