css-variables-polyfill
css-variables-polyfill copied to clipboard
Variables with "var(...)" values
Hello,
I faced a problem in a project where one was my variables was assigned as another one (e.g. --var1: var(--var2);). I managed to solve it by modifying replaceGetters like this, so it will keep iterating through the CSS as long as matches are found:
replaceGetters: function(curCSS, varList) {
// console.log(varList);
let replaced = true;
while (replaced) {
replaced = false;
for (let theVar in varList) {
// console.log(theVar);
// match the variable with the actual variable name
let getterRegex = new RegExp('var\\(\\s*' + theVar + '\\s*\\)', 'g');
// console.log(getterRegex);
// console.log(curCSS);
if (curCSS.search(getterRegex, varList[theVar])>=0) {
curCSS = curCSS.replace(getterRegex, varList[theVar]);
replaced = true;
}
// now check for any getters that are left that have fallbacks
let getterRegex2 = new RegExp('var\\([^\\)]+,\\s*([^\\)]+)\\)', 'g');
// console.log(getterRegex);
// console.log(curCSS);
let matches = curCSS.match(getterRegex2);
while (matches) {
// console.log("matches",matches);
matches.forEach(function(match) {
// console.log(match.match(/var\(.+,\s*(.+)\)/))
// find the fallback within the getter
curCSS = curCSS.replace(match, match.match(/var\([^\)]+,\s*([^\)]+)\)/)[1]);
replaced = true;
});
}
// curCSS = curCSS.replace(getterRegex2,varList[theVar]);
};
};
// console.log(curCSS);
return curCSS;
},
Would be good if this were made into a pull request and added. :)
FWIW I use CSS variables to point to other variables all the time 🙂 +1 to this functionality