Search code examples
sassfrontendfile-structure

Sass 7-1 Pattern using @use and @forward


What's the correct way of setting up a Sass 7-1 Pattern using @use and @forward?

Example:

Sass 7-1 Pattern

Files:

./scss/abstracts/_variables.scss

$main-color: #222222;

./scss/abstracts/_index.scss

@forward './variables';

./scss/components/_card.scss

.card {
  color: $main-color;
}

./scss/components/_index.scss

@forward './card';

./index.scss

@use './scss/abstracts/index' as *;
@use './scss/components/index' as *;

If @use and @forward were replaced by @import (which the docs say is deprecated) it would work but when using the new @use and @forward Syntax the card component which is imported after abstracts is not able to "see" the variables.

It works if abstracts/_index.scss is imported via @use into components/_card.scss.

If I were to use Sass 7-1 Pattern, is duplicating @use on multiple files across the 7 folders the correct approach? It seems like it kind of kills the need of a main Sass file importing all partials.

To whoever tries to enlighten me, I thank you in advance!


Solution

  • After consulting SASS @import documentation

    Looks like it's being deprecated because it makes all imports global across the files from the point it's imported, making it easier to cause name-collision between multiple libraries.

    You'll need to implement @use across your files but as said into @use documentation about the main differences between @import and @use:

    @use only makes variables, functions, and mixins available within the scope of the current file. It never adds them to the global scope. This makes it easy to figure out where each name your Sass file references comes from, and means you can use shorter names without any risk of collision.

    And it's nice to keep in mind that:

    @use only ever loads each file once. This ensures you don’t end up accidentally duplicating your dependencies’ CSS many times over.

    So for your code to work just add to

    @use "../abstracts/index" as *;
    
    .card {
        color:$main-color;
    }