How To Use Sass @use And @forward

Sass is a popular CSS preprocessor that extends the functionality of CSS by adding features such as variables, mixins, and nesting. One of the key features of Sass is the ability to use modular code through the use of partials, which are small Sass files that can be imported into other Sass files.

The @use and @forward directives are two ways to import partials into a Sass file. The @use directive creates a namespace for the imported partial, which can help avoid naming conflicts and improve performance. The @forward directive allows you to re-export (or “forward”) content from one part to another, which can be helpful in creating a facade module or splitting up a large module into smaller pieces.

Here’s a breakdown of each directive and how they differ;

@use

The @use directive is used to import a Sass module into a file, and it has a few different benefits over the older @import directive:

  • It creates a namespace for the module, which helps avoid naming conflicts with variables and mixins in other modules.
  • It only loads the code that is actually used from the module, which can help improve performance.
  • It can import non-Sass modules (such as plain CSS files), which the @import directive cannot do.

To use @use, you write @use followed by the path to the module file, like this;

@use 'path/to/module';

You can also specify an alias for the module namespace, like this;

@use 'path/to/module' as myModule;

Then, you can reference variables, mixins, and other content from the module using the namespace and the . operator, like this;

.my-class {
  color: myModule.$my-color;
  @include myModule.my-mixin();
}

@forward

The @forward directive is used to re-export (or “forward”) content from one module to another. This can be useful if you want to split up a large module into smaller pieces, or if you want to create a facade module that exposes a simplified interface to other modules.

To use @forward, you write @forward followed by the name(s) of the content you want to forward, like this;

@forward 'path/to/module' (my-variable, my-mixin);

You can also specify an alias for the forwarded content, like this;

@forward 'path/to/module' (my-variable as myAlias, my-mixin as myOtherMixin);

Then, in the file where you want to use the forwarded content, you use @use to import the module and its forwarded content, like this;

@use 'path/to/module' as myModule;
.my-class {
  color: myModule.myAlias;
  @include myModule.myOtherMixin();
}

Note that the @use directive is still needed to actually import the module, even though the content is forwarded. Also, any changes made to the forwarded content in the importing module will not affect the original module.

Other Blogs about Sass:

Reference

Leave a Comment

Your email address will not be published. Required fields are marked *