string-extract-sass-vars1.2.8

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";

assert.deepEqual(
  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

§ API

extractVars(inputString, [opts]);

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

§ API - Input

Input argumentTypeObligatory?Description
inputStringStringyesString 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 Nunjucksopens in a new tab, we need to load the variable textGrey into Nunjucks global Environmentopens 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).

§ Licence

MITopens in a new tab

Copyright © 2015–2020 Roy Revelt and other contributors

Related articles:

ARTICLE  
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 5.11.6
Extracts, cleans and encodes text
📦 string-match-left-right 4.0.13
Match substrings on the left or right of a given index, ignoring whitespace
📦 string-split-by-whitespace 1.6.71
Split string into array by chunks of whitespace
📦 string-collapse-white-space 5.2.30
Efficient collapsing of white space with optional outer- and/or line-trimming and HTML tag recognition
📦 string-range-expander 1.11.10
Expands string index ranges within whitespace boundaries until letters are met
📦 string-remove-duplicate-heads-tails 3.0.72
Detect and (recursively) remove head and tail wrappings around the input string
📦 string-uglify 1.2.46
Shorten sets of strings deterministically, to be git-friendly