Handling SCSS variables at scale
Variables in SCSS are a wonderful thing but they can quickly get out of hand, trying to maintain them across several files without accidentally reassigning them or keeping track of where they originated or what their scope is supposed to be.
The problem fundamentally is that SCSS has no concept of locally scoped variables, much like CSS itself, everything is in the global namespace.
I’ve adopted a pattern that I’ve used in my projects for the last couple of years where scoping is emulated using a simple naming convention.
I have a single
_variables.scss file which contains all my “global” variables. These are all prefixed
g- to easily identify them across the app.
// Font scale
g- flag indicates they are intended to be used across multiple files.
Then in my component files I have a set of variables declared at the top of the file. For example if I had an accordion component I would set out the file along the following lines:
This is obviously a contrived example, but I have found this pattern to be hugely beneficial on huge projects with large numbers of components and app-wide variables to keep track of.
It is important to note that local component / module variables should exclusively be used in their component files in order to emulate local scope.