Find Unused CSS Across Entire Web Project [Local]?

1 points by Normille ↗ HN
Hoping the collective wisdom of HN can help me with this one:

I'm currently archiving a site for a client which was built in WordPress [I know! I know!] by creating a static version from it. So I've used `curl` to download the entire site and spent a few days stripping out the tangled mess of WordPress cruft.

Next in my sites is the CSS. I've consolidated the eleventy billion CSS files strewn throughout WP into one central CSS file, which is about 3000 lines long. And now need to strip out all the unused selectors... of which I suspect there are many, because the site is mostly just plain text articles with occasional illustrations. No fancy-schmancy stuff at all.

Plenty of advice on the web about using Chrome Dev tools to check for unused CSS against a single page. But this is a site of 500+ pages, so I need something that will crawl the entire project and compile a list of all the CSS used/unused across the entire site.

On the face of it this seems like one of those horribly repetitive tasks which would be a nightmare for a human to do, but trivial for a computer. A solution wouldn't even need to automagically strip the CSS out. Even just marking the used elements would allow me to see what was required or not and manually delete the rest. Pseudo-code-ually:

  for HTML file in project 
  look for class=XXX or id=#YYY
  look through project CSS file for .XXX or #YYY
  insert comment /*this is used in file ZZZ.html*/
Anyone got any suggestions before I embark on the chore of trying to script something myself? The web project is stored locally. So I can either traverse it as a series of files or access it through a browser on localhost. It's all plain ol' HTML.

1 comment

[ 6.5 ms ] story [ 18.4 ms ] thread
You can try automating it with puppeteer by programmatically accessing the coverage data

    await page.coverage.startCSSCoverage()
    await page.goto('https://example.com/')
    await page.coverage.stopCSSCoverage()