从 Chrome下载 Coverage .json
(>= v73) [ DevTools 中的新功能 - Chrome 73 ]。
您可以使用此节点脚本提取 CSS:
$ node extractCSS.js ~/Desktop/Coverage-20190325T110812.json
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
https://d33wubrfki0l68.cloudfront.net/css/1bd6a34e1fcf409d29d1a960e6299893fca2e7b1/css/all.css
https://unpkg.com/bootstrap@4.1.3/dist/css/bootstrap.min.css
./final_css.css file saved
// extractCSS.js
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');
});
https://gist.github.com/gianpaj/a2f99e022e2c3f8abb9deecb47d572c4
灵感来源:https ://blog.fullstacktraining.com/remove-unused-css-javascript-code-from-your-project/