Parse SASS variables file into a plain object of CSS key-value pairs

§ Quick Take

import { strict as assert } from "assert";
import { extractVars } from "string-extract-sass-vars";

  extractVars(`// all variables are here!!!
// ------------------------------------------
$red: #ff6565; // this is red
// $green: #63ffbd; // no green here
$yellow: #ffff65; // this is yellow
$blue: #08f0fd; // this is blue
$fontfamily: Helvetica, sans-serif;
$border: 1px solid #dedede;
$borderroundedness: 3px;
$customValue1: tralala;
$customValue2: tralala;
// don't mind this comment about #ff6565;
$customValue3: 10;`),
    red: "#ff6565",
    yellow: "#ffff65",
    blue: "#08f0fd",
    fontfamily: "Helvetica, sans-serif",
    border: "1px solid #dedede",
    borderroundedness: "3px",
    customValue1: "tralala",
    customValue2: "tralala",
    customValue3: 10,

§ Examples


extractVars(str, [opts])

In other words, it is a function which takes two input arguments, a string and an optional options object (above, those square brackets mean "optional").

§ API - Input

Input argumentTypeObligatory?Description
strStringyesString to process
optional options objectPlain objectnoSee below

For example, a typical input for this program:

$red: #ff6565;
$blue: #08f0fd;

§ Options Object, opts

Options Object's keyThe type of its valueDefaultObligatory?Description
throwIfEmptyBooleanfalsenoFor extra insurance, you can set this program to throw if it didn't extract any keys. Not enabled by default.
cbFunctionnullnoPut a function here to process each value.

Here are all defaults in one place:

throwIfEmpty: false,
cb: null,

§ API - Output

Returns a plain object of zero or more SASS file's key-value pairs.

For example, a typical output of this program:

red: "#ff6565",
blue: "#08f0fd"

§ opts.throwIfEmpty

In production, you have many things to worry about. Imagine something went wrong with your SCSS variables file - or it was mangled - or something else went wrong - this program would find no variables and would yield an empty plain object. But you would not notice.

If you know that there will always be at least one key in the extracted source — set opts.throwIfEmpty — it will throw an error instead of silently yielding an empty plain object.

By default, this option is disabled.

§ opts.cb

Think of it as a middleware — if you pass a function, then before placing the extracted value into a result object, this program will feed that value into your function and use function's result instead.

This gives opportunities to process the values, for example, turning 3-digit hex colour numbers into email-friendly 6-digit:

§ What this program doesn't do

This program is a quick parser for variables files or simple key-value pair SASS style content. It's not a fully-fledged SASS code parser.

Please, no fancy bits:

  • No nesting
  • No partials
  • No modules
  • Mixins
  • No extend/inheritance
  • No operators

§ Why do you need this

Sometimes we want to use CSS variables in the inline HTML styles. For example, <span style="color: ;"></span>.

It depends on what templating engine you use, but in case of Nunjucks opens in a new tab, we need to load the variable textGrey into Nunjucks global Environment opens in a new tab.

In Gulp (or Eleventy or other script which runs everything) you use Node fs.readFileSync to read the PostCSS/SASS variables file, containing line $textGrey: #ccc;. Then you feed that outout into this program which parses and extracts a plain object: { textGrey: "#ccc" }. Then you load it into Nunjucks global Environment.

After that, <span style="color: ;"></span> is rendered into <span style="color: #ccc;"></span>.

Conceptually, global variables in HTML and CSS allow us to DRY the code — there's single source of truth for constants. In React component-based web development Storybook-documented colour constants is a similar thing.

And global variables are not just for HTML inline CSS use:

  1. You can put Nunjucks globals into SASS variables file - your CSS won't use them but all global constants will be in one place: both CSS and Nunjucks.
  2. Template's logic can use SASS variables file values in calculations (imagine, column count).

§ Changelog

See it in the monorepo opens in a new tab, on GitHub.

§ Contributing

To report bugs or request features or assistance, raise an issue on GitHub opens in a new tab.

Any code contributions welcome! All Pull Requests will be dealt promptly.

§ Licence

MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related articles:

Our Dark Mode Setup

Our Dark Mode Setup

Conceptually, dark/light mode on a website is driven by the buttons on the UI: whichever mode user picks, a data-theme attribute with that value gets set on <html> tag. We also persist that to browser's local storage.

Automatic mode setting "listens" to system's setting via @media (prefers-color-scheme: dark). Manual dark/light modes' CSS "listens" to <html> tag attribute's value by :root[data-theme='dark'].

That's pretty much it.

Here is the mixin we use.

Read article Our Dark Mode Setup

Related packages:

📦 detergent 7.0.16
Extracts, cleans and encodes text
📦 string-range-expander 2.0.16
Expands string index ranges within whitespace boundaries until letters are met
📦 string-collapse-leading-whitespace 5.0.16
Collapse the leading and trailing whitespace of a string
📦 string-find-heads-tails 4.0.16
Finds where are arbitrary templating marker heads and tails located
📦 string-overlap-one-on-another 2.0.16
Lay one string on top of another, with an optional offset
📦 string-left-right 4.0.16
Looks up the first non-whitespace character to the left/right of a given index
📦 string-match-left-right 7.0.10
Match substrings on the left or right of a given index, ignoring whitespace