sass

Use !default value with @use in SCSS


I am having some difficulty overwriting !default values in SCSS while using @use. When I use @import instead of @use it behaves correctly but while using @use the console gives an error (This module and the new module both define a variable named "$variable-name").

When I change the variable inside the same file where I assign the variable to an element it behaves correctly:

// variables/variable.scss
$color-accent: red !default;

// variables/index.scss
@forward ./variable.scss;

// change.scss
@use './variables/index' as *;
$color-accent: blue;
body {
  background-color: $color-accent;
}

// body background color is blue

But when I try overwriting it in a seperate file it won't work:

// change.scss
$color-accent: blue;

// variables/index.scss
@forward ./variable.scss;
@forward ./change.scss;

// base.scss
@use './variables/index' as *;
body {
  background-color: $color-accent;
}

// main.scss
@use './base';

// error: Two forwarded modules both define a variable named $color-accent

Also, when I only @forward the variable.scss and @use the change.scss in the main.scss file it doesn't give the right outcome (body background color stays red without an error).

Does anyone have a suggestion? All help is appreciated.

Joop


Solution

  • The error is where you used two @forward in index.scss and these two files have variables with the same name. Just loading the change.scss file with @import can solve the problem.

    More Information about the difference between @import, @use and @forward is here: https://www.liquidlight.co.uk/blog/use-and-import-rules-in-scss/.

    // variables/index.scss
    @forward "./variable.scss";
    @import "./change.scss";