Chrome Devtools Coverage: how to save or capture code used code?

雨燕双飞 提交于 2019-12-02 20:07:34
stereobooster

You can do this with puppeteer

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage()

  //Start sending raw DevTools Protocol commands are sent using `client.send()`
  //First off enable the necessary "Domains" for the DevTools commands we care about
  const client = await page.target().createCDPSession()
  await client.send('Page.enable')
  await client.send('DOM.enable')
  await client.send('CSS.enable')

  const inlineStylesheetIndex = new Set();
  client.on('CSS.styleSheetAdded', stylesheet => {
    const { header } = stylesheet
    if (header.isInline || header.sourceURL === '' || header.sourceURL.startsWith('blob:')) {
      inlineStylesheetIndex.add(header.styleSheetId);
    }
  });

  //Start tracking CSS coverage
  await client.send('CSS.startRuleUsageTracking')

  await page.goto(`http://localhost`)
  // const content = await page.content();
  // console.log(content);

  const rules = await client.send('CSS.takeCoverageDelta')
  const usedRules = rules.coverage.filter(rule => {
    return rule.used
  })

  const slices = [];
  for (const usedRule of usedRules) {
    // console.log(usedRule.styleSheetId)
    if (inlineStylesheetIndex.has(usedRule.styleSheetId)) {
      continue;
    }

    const stylesheet = await client.send('CSS.getStyleSheetText', {
      styleSheetId: usedRule.styleSheetId
    });

    slices.push(stylesheet.text.slice(usedRule.startOffset, usedRule.endOffset));
  }

  console.log(slices.join(''));

  await page.close();
  await browser.close();
})();

I talked with the engineer who owns this feature. As of Chrome 64 there's still no way to export the results of a coverage analysis.

Star issue #717195 to help the team prioritize this feature request.

  1. first of all you need to download and install "Google Chrome Dev".
  2. on Google chrome Dev go to Inspect element > Sources > Ctrl+shift+p
  3. Enter "coverage" and select "Start Instrumenting coverage and reload Page"
  4. Then use Export icon

    this will give you a json file.

you can also visit : Chrome DevTools: Export your raw Code Coverage Data

Chrome canary 73 can do it. You will need Windows or Mac OS. There is an export function (Down arrow icon) next to the record and clear buttons. You'll get a json file and then you can use that to programmatically remove the unused lines.

I downloaded the latest version of canary and the export button was present.

I then used this PHP script to parse the json file returned. (Where key '6' in the array is the resource to parse). I hope it helps someone!

$a = json_decode(file_get_contents('coverage3.json'));
$sText = $a[6]->text;
$sOut = "";
foreach ($a[6]->ranges as $iPos => $oR) {
    $sOut .= substr($sText, $oR->start, ($oR->end-$oR->start))." \n";
}
echo '<style rel="stylesheet" type="text/css">' . $sOut . '</style>';

You can do this with Headless Chrome and puppeteer:

  1. In a new folder install puppeteer using npm (this will include Headless Chrome for you):

npm i puppeteer --save

  1. Put the following in a file called csscoverage.js and change localhost to point to your website.

:

const puppeteer = require('puppeteer');
const util = require('util');
const fs    = require("fs");

(async () => {
 const browser = await puppeteer.launch();
 const page = await browser.newPage();
 await page.coverage.startCSSCoverage();
 await page.goto('https://localhost'); // Change this
 const css_coverage = await page.coverage.stopCSSCoverage();
 console.log(util.inspect(css_coverage, { showHidden: false, depth: null }));
 await browser.close();

let final_css_bytes = '';
let total_bytes = 0;
let used_bytes = 0;

for (const entry of css_coverage) {
  final_css_bytes = "";

  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';
  }

  filename = entry.url.split('/').pop();

  fs.writeFile('./'+filename, final_css_bytes, error => {
    if (error) {
      console.log('Error creating file:', error);
    } else {
      console.log('File saved');
    }
  });
}
})();
  1. Run it with node csscoverage.js

This will output all the CSS you're using into the separate files they appear in (stopping you from merging external libraries into your own code, like the other answer does).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!