Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Last active December 20, 2023 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbreckmckye/fada286c6c2c5e8fee9e26be205e2b92 to your computer and use it in GitHub Desktop.
Save jbreckmckye/fada286c6c2c5e8fee9e26be205e2b92 to your computer and use it in GitHub Desktop.
Analysing CSS compilation
// Get classnames from document or string. Look up locations. Handy for diagnosing bad CSS-in-JS classes like "class='undefined'"
function classNames(html) {
const classStrings = Array.from(html.matchAll(/class=".+?"/g)).flat()
const classes = classStrings.map(str => {
const [ _start, class_, names, _quot, _end ] = str.split(/(class="|")/g)
return names.split(' ')
})
const classMap = classes.reduce(
(acc, classNames, elementIndex) => {
for (const name of classNames) {
acc[name] = acc[name] || []
acc[name].push(elementIndex)
}
return acc
},
{}
)
return {
classMap,
lookup(index) {
const classNames = classes[index]
// attr selector to tolerate classnames like "16px"
const selector = `[class="${classNames.join(' ')}"]`
return document.querySelector(selector)
}
}
}
function docHtml() {
return new XMLSerializer().serializeToString(document.documentElement)
}
function compare(classNames1, classNames2) {
const keys1 = Object.keys(classNames1.classMap)
const keys2 = Object.keys(classNames2.classMap)
const result = {
firstOnly: [],
both: [],
secondOnly: []
}
for (const key of keys1) {
if (keys2.includes(key)) {
result.both.push(key)
} else {
result.firstOnly.push(key)
}
}
for (const key of keys2) {
if (!keys1.includes(key)) result.secondOnly.push(key)
}
return result
}
# Prettify compiled CSS. Useful for stripping out compiled CSS / CSS module differences
cp file.whatever.css file.cleaned.css
node_modules/.bin/prettier file.cleaned.css --write --no-config
# thanks https://sed.js.org/ !
sed -i -r 's|G\w{6}|classname|g' file.cleaned.css
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment