'Sass combine @forward and @use

I'm trying to migrate to the new modular sass, and have two files I want to export from a common utils module:

utils/_functions.scss

@function color($key) {
  @return map-get($colors, $key);
}

utils/_variables.scss

$colors: (
  primary: 'red',
  secondary: 'blue',
);

I'm trying to export it like this:

utils/_index.scss

@forward 'variables';
@forward 'functions';

But I get a compilation error SassError: Undefined variable, because $colors is not defined in function.

I would like to have a way to combine @forward and @use like this:

utils/_functions.scss

@use '../variables'

@function color($key) {
  @return map-get(variables.$colors, $key);
}

Is that possible?



Solution 1:[1]

Indeed you have to @use the variables file in every file you need it. In this case you needd utils/variables in utils/functions but you do not @use it there.

Additional hint:

There are two additional issuses in your code, - but they do not affect the error in your question:

  1. You should setup variables in modules as !defaults so they can be changed/overwritten when you @use them.
  2. You have an error in your map. You setup the colors as string (= primary: 'red'). The result is that the value will be handeld as string and not as color which leads to a wrong css code.

Following code should work:



//###> file: utils/variables

$colors: (
  primary: red,
  secondary: blue,
) !default;



//##> file: utils/functions

@use 'variables' as *;

@function color($key) {
    @return map-get($colors, $key);
}



//##> file: utils/index

@forward 'variables';
@forward 'functions';



//##> file main

@use 'utils' as *; 

.class {
    color: color( primary );
}

//---> compiles to css

.class {
  color: red;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1