Skip to content

Instantly share code, notes, and snippets.

@gianpaj
Created March 25, 2019 09:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gianpaj/a2f99e022e2c3f8abb9deecb47d572c4 to your computer and use it in GitHub Desktop.
Save gianpaj/a2f99e022e2c3f8abb9deecb47d572c4 to your computer and use it in GitHub Desktop.
Extract used CSS from a page
# Extract used CSS from a page
# https://stackoverflow.com/a/55334749/728287
#
# $ node extractCSS.js ~/Desktop/Coverage-20190325T110812.json
const fs = require('fs');
let final_css_bytes = '';
let total_bytes = 0;
let used_bytes = 0;
const filename = process.argv[2]
const output = './final_css.css'
if(!filename) {
console.error('Missing filename to get coverage information from');
process.exit();
}
const file_coverage = fs.readFileSync(filename);
const css_coverage = JSON.parse(file_coverage);
for (const entry of css_coverage) {
if (!entry.url.endsWith('.css')) continue;
console.log(entry.url)
final_css_bytes += '# ' + entry.url + '\n\n'
total_bytes += entry.text.length;
for (const range of entry.ranges) {
used_bytes += range.end - range.start - 1;
final_css_bytes += entry.text.slice(range.start, range.end) + '\n';
}
final_css_bytes += '\n\n'
}
fs.writeFile(output, final_css_bytes, error => {
if (error) {
console.log('Error creating file:', error);
return
}
console.log(output, 'file saved');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment