Migrating SCSS Imports to Use/Forward: Handling Shared Variables
question should be like,
i wanted to update my sass and remove the warning for import since its deprecating.
this is how my structure is.
scss
┣ Component
┃ ┗ _variable.scss
┃ ┣ _reboot.scss
┃ ┗ _utilities.scss
┃ ┣ _card.scss
┃ ┗ _grid.scss
┃ ┣ _sidebar.scss
┃ ┣ _table.scss
┃ ┣ _button.scss
┃ ┣ _form.scss
┃ ┣ _container.scss
┃ ┣ _badge.scss
┃ ┗ _grid.scss
┗ style
┃ ┗ style.scss
all the scss inside of the components were being imported to style.scss like this below:
//style.scss
@import "../components/variables";
@import "../components/reboot";
@import "../components/container";
@import "../components/grid";
@import "../components/badge";
@import "../components/tables";
@import "../components/forms";
@import "../components/buttons";
I need to update my Sass code to use the newer @use/@forward syntax instead of @import. My main concern is handling the _variables.scss file, which contains shared variables used across all components.
What's the best way to structure this with @use/@forward? Specifically:
1. Should I @use '_variables.scss' in each component file individually?
2. Or is there a more efficient way to share these variables across components without duplicating the @use statement?
3. What changes would I need to make to style.scss to properly load all components with their dependencies?4 Replies
you cant
import and use/forward are very different
you will have to rewrite quite a lot, depending on how you used imports
since you werent using the imports to their full power, you probably can get away with just throwing everything into mixins or something
Sass: Migrator
Syntactically Awesome Style Sheets
should help 🙂
What's the best way to structure this with @use/@forward? Specifically: Should I @use '_variables.scss' in each component file individually? Or is there a more efficient way to share these variables across components without duplicating the @use statement? What changes would I need to make to style.scss to properly load all components with their dependencies?You can collect them all into an
_index.scss
, for each one of your folders.
So like, /components/_index.scss
has a @forward
for every one of those folders you listed above.
Then, you can do a @use components
and it has access to everything in there.by the way, the
@forward
has an option to add a prefix, so you dont have to write buttons-abc
, buttons-xyz
, buttons-jkl
...
also, contrary to @import
, you have to @use
all the modules you want, IN EVERY SINGLE FILE you want to use them
doing what kevin said is a good idea, so you only do a single @use
for each file in your project
and honestly, if i were you, i would consider having 2 files: styles and critical
in the critical file, all you do is creating the css variables you need and setting up the very very very basics of your site
you then can just send that tiny portion of css as part of the html or just ignore this part and keep doing what you are doing