Checking for missing references when using custom properties

- Posted in css webdev workflow

When you declare a variable with SCSS, like so:

$red: #FF0000;

And you use it somewhere, but you make an error…

.my-code {
  color: $redy;
}

…the compiler will warn you. In fact the project probably won’t compile.

This prevents you from making a wrong reference. This type of bug is a “wrong reference bug” i.e. we are referencing the wrong thing.

But if you use custom properties, you won’t know if you did something wrong. A color might just fall back to black or the body color and you won’t know if you did something wrong.

:root {
  --red: #FF0000;
}

.my-code {
  color: var(--redy); /* This error won't be caught! */
}

I recently wanted to make sure I didn’t have any wrong references and had an idea. We can leverage the “fallback” aspect of a custom property to get a visual cue:

:root {
  --red: #FF0000;
}

.my-code {
  color: var(--redy, hotpink);
}

What I do in practice is change all variable names temporarily to provide this fallback value (with a regex: replace var\(\-\-(.*)\) by var(--$1, hotpink)), then click through my project to search for anything that looks like the fallback color, in this case hotpink.

Leave a Reply

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