postcss-extract-custom-properties
PostCSS plugin to extract CSS Custom Properties information.
Installation
npm install postcss-extract-custom-properties --save-dev
Parses input.css
:
in to output.json
Why?
To create a fallback for browsers that do not support CSS Custom Properties.
Useful for dynamic themeing. See Dynamic Custom Properties.
Usage
// dependenciesvar fs = ;var postcss = ;var extractCustomProperties = ; // css to be processedvar css = fs; // file path to write resultsvar output = './build/output.json'; // process css using postcss-extract-custom-properties ;
Constraints
- CSS Variables must not be used on a shortened property.
Dynamic Custom Properties
For browsers that do not support CSS Custom Properties and the :root
selector.
Parse output.json
in to <style>
elements for each variable.
Replace the variable placeholders (@baseColor
, @sizeH1
and @accentColor
in the example above).
Now we can target all selectors that reference these variables.
To change the variable, we can replace the value programatically.
// Reference to CSS sring created from JSONvar baseColorString = `a, .class2 li:first-child { color: @baseColor; }.class1 { background-color: @baseColor; }`;// Value to insert in place of placeholdervar newBaseColor = '#00CC00';// Regex replace all occurances in stringvar re = '@baseColor' 'g';var newBaseColorString = baseColorString;// Style element to updatevar baseColorStyleElem = document;// Replace innerHTML value with updated CSSbaseColorStyleEleminnerHTML = newBaseColorString;
See PostCSS docs for examples for your environment.