Last active
September 28, 2020 09:33
-
-
Save adrienZ/0257e37bf4788b903ba76fa82dac1ed1 to your computer and use it in GitHub Desktop.
Convert a javascript object into a string of sass variables
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
/** | |
* @name jsToSassVariables | |
* @param {Object} obj | |
* @returns {String} | |
*/ | |
function jsToSassVariables(obj) { | |
const { stringify, parse } = JSON | |
// remove null, undefined values and functions | |
const objStr = stringify(obj) | |
const objParsed = parse(objStr, (key, value) => { | |
if (key.length === 0) return value | |
// lists | |
if (Array.isArray(value)) { | |
return value.join(', ') | |
} | |
if (typeof value === 'number' || typeof value === 'boolean') { | |
return value.toString() | |
} | |
// object to sass map | |
if (value instanceof Object) { | |
let subkeys = '(' | |
subkeys += Object.keys(value) | |
.map(subkey => `"${subkey}": ${value[subkey] || ''}`) | |
.join(', ') | |
subkeys += ')' | |
return subkeys | |
} | |
// default | |
return value | |
}) | |
const objAsStrings = Object.keys(objParsed).map(varName => { | |
return `$${varName}: unquote(${JSON.stringify(objParsed[varName])})` | |
}) | |
const resString = objAsStrings.join('; ') + ';' | |
return resString | |
} | |
module.exports = jsToSassVariables; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment