Is there anyway to import a regular CSS file with Sass\'s @import
command? While I\'m not using all of the SCSS syntax from sass, I do still enjoy it\'s combini
I figured out an elegant, Rails-like way to do it. First, rename your .scss
file to .scss.erb
, then use syntax like this (example for highlight_js-rails4 gem CSS asset):
@import "<%= asset_path("highlight_js/github") %>";
Why you can't host the file directly via SCSS:
Doing an @import
in SCSS works fine for CSS files as long as you explicitly use the full path one way or another. In development mode, rails s
serves assets without compiling them, so a path like this works...
@import "highlight_js/github.css";
...because the hosted path is literally /assets/highlight_js/github.css
. If you right-click on the page and "view source", then click on the link for the stylesheet with the above @import
, you'll see a line in there that looks like:
@import url(highlight_js/github.css);
The SCSS engine translates "highlight_js/github.css"
to url(highlight_js/github.css)
. This will work swimmingly until you decide to try running it in production where assets are precompiled have a hash injected into the file name. The SCSS file will still resolve to a static /assets/highlight_js/github.css
that was not precompiled and doesn't exist in production.
How this solution works:
Firstly, by moving the .scss
file to .scss.erb
, we have effectively turned the SCSS into a template for Rails. Now, whenever we use <%= ... %>
template tags, the Rails template processor will replace these snippets with the output of the code (just like any other template).
Stating asset_path("highlight_js/github")
in the .scss.erb
file does two things:
rake assets:precompile
task to precompile the appropriate CSS file.This also means that the SCSS engine isn't even parsing the CSS file; it's just hosting a link to it! So there's no hokey monkey patches or gross workarounds. We're serving a CSS asset via SCSS as intended, and using a URL to said CSS asset as Rails intended. Sweet!