!default is a Sass flag that indicates conditional assignment to a variable — it assigns a value only if the variable was previously undefined o

Creating Stylesheet Feature Flags With Sass !default

submited by
Style Pass
2021-05-29 04:28:55

!default is a Sass flag that indicates conditional assignment to a variable — it assigns a value only if the variable was previously undefined or null. Consider this code snippet:

After running these two lines, the value of $variable is still 'hello world' from the original assignment on line 1. In this case, the !default assignment on line 2 is ignored since a value has already been provided, and no default value is needed.

The primary motivation behind !default in Sass is to facilitate the usage of style libraries, and their convenient inclusion into downstream applications or projects. By specifying some of its variables as !default, the library can allow the importing application to customize or adjust these values, without completely forking the style library. In other words, !default variables essentially function as parameters which modify the behavior of the library code.

The important distinction here, and the reason @use...with is preferable, is about the scope of the overrides. The with block makes it crystal clear — to both the Sass compiler and anyone reading the source code — that the overrides apply specifically to variables which are defined and used inside of library.scss. Using this method keeps the global scope uncluttered and helps mitigate variable naming collisions between different libraries.

Leave a Comment