Search code examples
csssasscolors

@use not working in Sass to import variables but @import is working


I have a sass variable declared in the file _variables.scss. When I import that file using @use, I get an error when compiling stating "Error: undefined variable". If however, I use @import instead, everything compiles just fine.

Here's the first file which is imported

//_variables.scss
$primaryColor: rgba(199, 26, 113, 0.747);

And here's the file which is doing the importing.

//styles.scss
@use 'variables';

header {
background: $primaryColor;
}

When compiling this returns "Error: undefined variable". But if I change @use to @import, it works just fine.

Why does @import work but @use does not?


Solution

  • Variables imported with @use have a namespace. Therefore, you need to prefix your variable name with the namespace (i.e. instead of $primaryColor, write variables.$primaryColor):

    @use 'variables';
    // @use './variables' // creates the same namespace
    
    header {
      background: variables.$primaryColor;
    }
    

    You can also rename the namespace:

    @use 'variables' as 'renamedVariables';
    
    header {
      background: renamedVariables.$primaryColor;
    }
    

    If you don't want to use the namespace, you can load variables without it:

    @use 'variables' as *;
    
    header {
      background: $primaryColor;
    }
    

    But imo namespaces make your stylesheet neater (e.g. it's clear where each variable comes from, and you won't accidentally overwrite one variable with another), so i'd stick with them...

    Another Stack Overflow answer pointed me in the right direction