SASS Variables and @use
January 28, 2024It's been a minute since I've used SASS variables extensively. So of course when looking to add some for viewport widths and thickness for my site, I had to look back up the docs on how to do them exactly.
I immediately went to search on the docs for the @import
syntax when the search result of "What's Wrong with @import
?" came up. Wait-- am I not supposed to use @import
? 😳
Turns out, no. From the SASS docs:
The Sass team discourages the continued use of the @import rule. Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead.
So what's this @use rule? 🤔 Turns out, it's just like import, but uses modules instead. 🎉
So, instead of all the variables being "globally" scoped whenever you import a file, they are namespaced like a module. For example, I created a styles/viewports.scss
file with the following contents:
$small: 430px;
Then, in my page.module.scss
file, I can import, I mean use, the viewports.scss
file like this:
@use '@/styles/viewports.scss';
And now I've got my viewports that I can reference for media queries like this:
@media (min-width: viewports.$small) {
...
}
I did the same thing with a styles/thickness.scss
file, so I can then do:
@use '@/styles/thickness.scss';
...
margin: thickness.$medium;
This feels so much better than having to worry about variable collisions with multiple imports, and also lets you name things more simply inside the variable files themselves (e.g. $small
instead of $smallViewport
).
Getting Back to it
January 27, 2024Restarting the ol' site. I'm hoping to post some simple example code and just practice my writing.