Created
June 23, 2018 21:23
-
-
Save alexkrolick/652718f1f6ca3f4decab7f9222634c5a to your computer and use it in GitHub Desktop.
Parse variables in a SASS file into an ES module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
In:
Out: