Sass — the map-merge pattern

An elegant solution for handling module configuration in Sass.

Stephen Pal-George
The Code Less Travelled

--

A rough and slightly brown-stained map of the world
Making use of maps (not this kind)

One of the many beautiful things about Sass is that it lets us write modules of CSS that we can then consume around the rest of our project. To give a very simplistic example, I might have a ‘color’ module that looks something like this:

// src/scss/color.scss$dark: #222;
$light: #FEFEFE;

Then, somewhere else entirely, I could use that module (and its members); maybe something like this:

// src/components/card.scss@use '../scss/color';.card {
background-color: color.$dark;
color: color.$light;
}

But here’s the thing — what if I wanted my colour module to be a bit more flexible? What if I wanted to write a module once that could be adapted, or configured, to any design system/colour palette? This is where the power of default variables comes into play. If we declare a variable as ‘default’ in our module, we can then override it when we consume the module. Let’s update our simple color example:

// src/scss/color.scss$dark: #222 !default;
$light: #FEFEFE !default;

--

--