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,



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 argument Type Obligatory? Description
str String yes String to process
optional options object Plain object no See below

For example, a typical input for this program:

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

Options Object, opts

Options Object's key The type of its value Default Obligatory? Description
throwIfEmpty Boolean false no For extra insurance, you can set this program to throw if it didn't extract any keys. Not enabled by default.
cb Function null no Put 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"


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.


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).


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


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.


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 8.0.1
Extracts, cleans and encodes text
📦 string-find-heads-tails 5.0.1
Finds where are arbitrary templating marker heads and tails located
📦 string-process-comma-separated 3.0.1
Extracts chunks from possibly comma or whatever-separated string
📦 string-collapse-white-space 10.0.1
Replace chunks of whitespace with a single spaces
📦 string-strip-html 9.0.1
Strips HTML tags from strings. No parser, accepts mixed sources
📦 string-convert-indexes 5.0.1
Convert between native JS string character indexes and grapheme-count-based indexes
📦 string-unfancy 5.0.1
Replace all n/m dashes, curly quotes with their simpler equivalents