Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

@use and namespaces

Every Sass file is a module. The @use rule loads a module and gives access to its members — variables, mixins and functions — through a namespace: a prefix with a dot, like variables.$primary. Thanks to namespaces, names from different files never collide.

Using a variable from another file

Create styles/abstracts/_variables.scss with the site's constants:

// styles/abstracts/_variables.scss
$primary: #2563eb;
$radius: 8px;

The button file loads it and refers to the variables through the namespace. By default the namespace is the last part of the path without the underscore — here variables:

// styles/components/_buttons.scss
@use "../abstracts/variables";
 
.btn {
  background: variables.$primary;
  border-radius: variables.$radius;
}
// styles/main.scss
@use "components/buttons";
.btn {
  background: #2563eb;
  border-radius: 8px;
}

The variables file itself prints nothing: it contains no rules, only values.

A shorter namespace

A long prefix can be renamed with as:

// styles/components/_cards.scss
@use "../abstracts/variables" as v;
 
.card {
  border-radius: v.$radius;
}

With as * the members are available without a prefix: $radius. This is convenient for your own variables file, but in a big project it becomes unclear where a name comes from. Use as * only for one or two files that every component needs.

A module is loaded once

If ten components @use the same variables file, its code runs once and its CSS, if any, appears in the output once. That is the main difference from the old @import, which copied the file every time.

Private members

A member whose name starts with - or _ is private: it is visible only inside its own file. Use it for helper values:

// styles/abstracts/_variables.scss
$-base: 4px;
$gap: $-base * 4;

Other files can read variables.$gap, but variables.$-base is an error.

Configuring a module

A variable marked !default takes this value only if nothing else was given. The file that loads the module can pass its own value with with:

// styles/abstracts/_theme.scss
$primary: #2563eb !default;
 
.link {
  color: $primary;
}
// styles/main.scss
@use "abstracts/theme" with ($primary: #16a34a);
.link {
  color: #16a34a;
}

This is how libraries such as Bootstrap let you change their colours without editing their files.

Common mistake

Every file must @use what it needs itself. Loading the variables in main.scss does not make them visible in components/_buttons.scss: Sass stops with Undefined variable or There is no module with namespace "variables". Add the @use line to the top of each file that uses the members.

Thanks for reading!

Donate to the site — we work hard for you.