Skip to content

Instantly share code, notes, and snippets.

@alexkrolick
Created June 23, 2018 21:23
Show Gist options
  • Save alexkrolick/652718f1f6ca3f4decab7f9222634c5a to your computer and use it in GitHub Desktop.
Save alexkrolick/652718f1f6ca3f4decab7f9222634c5a to your computer and use it in GitHub Desktop.
Parse variables in a SASS file into an ES module
const fs = require("fs");
const byline = require("byline");
const camelCase = require('lodash.camelcase')
const inputFile = "./colors.scss";
const outputFile = "./colors.js";
const sassVarDeclaration = /^\$(.*)\:\s(\S*)(?:\s\!default\;|\;)$/;
const isReference = val => val.startsWith("$");
const getReferenceName = val => val.slice(1);
async function main() {
// Read SCSS file line-by-line
const stream = byline(fs.createReadStream(inputFile, { encoding: "utf8" }));
// Process SCSS lines
const vars = new Map();
stream.on("data", line => {
const matched = line.match(sassVarDeclaration);
if (!matched) return;
const name = matched[1];
const value = matched[2];
if (isReference(value)) {
const referencedValue = vars.get(getReferenceName(value));
if (!referencedValue) {
throw Error(`Referenced SCSS variable '${value}' is not defined`);
}
vars.set(name, value);
} else {
vars.set(name, value);
}
});
// Write JS file
stream.on("finish", () => {
let outString = "";
vars.forEach((v, k) => {
const safeVariableName = camelCase(k)
outString = outString.concat(`export const ${safeVariableName} = "${v}"; // ${k}\n`)
});
fs.writeFile(outputFile, outString, () => console.log(outString));
});
}
main();
@alexkrolick
Copy link
Author

alexkrolick commented Jun 23, 2018

Example:

In:

// colors.scss
$blue = #00f;
$primary-color = $blue;

Out:

// colors.js
export const blue = "#00f"; // blue
export const primaryColor = "#00f"; // primary-color

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment