Understanding Sass @use and @forward

Sass discourages the use of @import now, so we’ve been updating our Drupal starter theme to use Sass modules. Sass modules can be imported with @use or with @forward, but they don’t do quite the same thing.

@use

@use loads a Sass stylesheet and makes the mixins, functions, and variables within that stylesheet available. They are namespaced unless you specifically load a module without a namespace.

With a namespace

@use "mixins/list";

.inline-list {
  @include list.inline;
}

Without a namespace

@use "mixins/list" as *;
.inline-list {
  @include inline;
}

@forward

@forward loads a Sass stylesheet and makes the mixins, functions, and variables available when that stylesheet is in turn used somewhere, similar to how @import worked. @forward lets you aggregate multiple mixins, functions, and/or variables into one sheet that you can then use whenever you load the stylesheet with @use.

// _mixins.scss
@forward "mixins/list";

// Some other stylesheet
@use "mixins";
.inline-list {
  @include mixins.inline;
}

@forward doesn’t actually include the module. If you want to use something from the forwarded module in the stylesheet that’s forwarding it, you need to load it with @use as well.

// _mixins.scss
@forward "mixins/list";
@use "mixins/list";

@mixin blue-inline {
  @include list.inline;
  color: blue;
}

// Some other stylesheet
@use "mixins";
.inline-list {
  @include mixins.inline;
}
.blue-list {
  @include mixins.blue-inline;
}
References