A utility to extract and pretty-print specific CSS classes which contain rules for properties which match the propsToGlean
array members.
Include the following code snippet in your React component where you want to run the CSS gleaning:
useEffect(() => {
const propsToGlean = [
'font',
'text',
'letter',
'white-space',
'line-height',
];
function gleanCSS() {
const stylesheets = Array.from(document.styleSheets);
const classRules = {};
for (const stylesheet of stylesheets) {
try {
for (const rule of stylesheet.cssRules) {
if (rule instanceof CSSStyleRule) {
const [selector, rules] = rule.cssText.split('{');
const cleanedRules = rules.replace('}', '').trim();
const propertiesArray = cleanedRules.split(';').filter(Boolean);
for (const property of propertiesArray) {
const [propertyName, propertyValue] = property.split(':');
for (const prop of propsToGlean) {
if (propertyName.trim().includes(prop)) {
classRules[rule.selectorText] = prettyPrintCss(rule.cssText);
}
}
}
}
}
} catch (e) {
console.log('gleanCSS error', e);
}
}
logReport(classRules);
}
function prettyPrintCss(cssRule) {
const [selector, properties] = cssRule.split('{');
const propertiesArray = properties.replace('}', '').split(';');
const formattedProperties = propertiesArray
.filter((property) => property.trim() !== '') // filter out empty strings
.map((property) => ` ${property.trim()};`)
.join('\n');
return `${selector.trim()} {\n${formattedProperties}\n}\n`;
}
function logReport(report) {
let str = '/* CSS Gleaned */\n\n';
for (const cssClass in report) {
str += report[cssClass];
}
console.log(str);
}
gleanCSS();
}, []);
- Add the above code to a React component within a
useEffect
hook to run the CSS gleaning process when the component mounts. - Modify the
propsToGlean
array to specify which CSS properties you want to extract. - The script will log the gleaned CSS rules to the console in a pretty-printed format.
The propsToGlean
array specifies which CSS properties to extract. By default, it includes:
font
text
letter
white-space
line-height
You can customize this array to include any properties you need.
This function iterates through all stylesheets and their rules in the document, extracting rules that contain the specified properties.
Formats the CSS rule into a readable string with proper indentation and newlines.
Logs the gleaned CSS rules to the console in a pretty-printed format.
When executed, the script will log something like the following to the console:
/* CSS Gleaned */
.className {
font-size: 16px;
line-height: 1.5;
}
.anotherClass {
text-align: center;
white-space: nowrap;
}
This output helps you see all the CSS rules containing the specified properties in a neat and organized manner.