Variable Scope, Defaults, and Configuration

Variable scope determines where a variable can be accessed. Variables declared at the top level are available throughout their relevant module scope, while variables declared inside blocks or functions may have more limited visibility.

Sass supports default assignments with !default. This flag assigns a value only when the variable is not already defined or is defined as null. It is useful for configurable libraries and themes.

The !global flag can update an existing global variable from a nested scope. Although valid in supported situations, global reassignment makes dependencies less explicit and should be avoided in ordinary component styling.

In the module system, configuration is commonly applied through @use with a with clause. The configured variables must be exposed appropriately by the module, generally using !default on the variables intended for configuration.

Avoid hidden global dependencies

Prefer explicit module configuration and parameters over repeated global variable reassignment. Explicit dependencies are easier to test and maintain.

Configurable Theme Tokens
$brand-color: #cc6699 !default;
$border-radius: 0.5rem !default;

.button {
  background-color: $brand-color;
  border-radius: $border-radius;
}
💡 The !default flag allows a variable to receive a value supplied by an appropriate configuration context when the module is loaded. It is especially useful for Sass libraries that expose customizable design tokens. For a module called theme, configuration can be supplied with @use "theme" with ($brand-color: #336699); when the module's configurable variables meet Sass's module configuration requirements.
Knowledge Check

What is the main purpose of the `!default` flag on a Sass variable?