Sassy Cascading Style Sheets, or SCSS, are one tool in the frontend developer’s toolkit to make their life easier. Prominent features (that I use) are nesting and variables. I’ve been using it in my own product, and I’m quite happy with it. Even if it is easy to make a bit of a mess (e.g., by nesting too much) it’s also a nice tool for building prototypes and MVPs.
Recently, I was refactoring my frontend code. There was one main.scss
file, a few (plain) javascript files that invoked some Vue stuff, and Django templates. I wanted to make use of the Single File Components (SFC) that Vue had to offer to make developing the frontend easier (and the feedback cycles shorter by using Hot Reloading). The conversion to SFCs is a story for some other time; In this post, I’ll show what I did to make my Vue SFCs play nice with the main.scss
file I was using. Specifically, I wanted to re-use the variables defined, but not have to @import
everything in every component.
A quick glance at the layout of the code that’s relevant to this post, before I show you the steps I used to make it happen:
. ├── static/ │ ├── main.scss # contained the variables and all style definitions ├── frontend/ │ ├── src │ │ ├── Component.vue # The newly created SFCs, containing ... # <style> tags that should include the variables
To re-use the variables that I used to define in main.scss
, I followed these steps:
frontend/src/scss/_variables.scss
main.scss
I added @import "../frontend/src/scss/_variables.scss
django-compress
, during runtime, we don’t need to find this actual file — it’s baked into the final CSS filestyle
tags automatically, by using the following fragment in frontend/vue.config.js
:css: { loaderOptions: { sass: { prependData: ` @import "@/scss/_variables.scss"; ` } }, },
When using the <style>
section of Vue’s SFCs, please remember to add the final compiled CSS from npm run build
to your <head>
too; this tripped me up when I used the technique above, and my newly written styles didn’t end up in the final build.