首页 文章

Chrome Devtools覆盖范围:如何保存或捕获代码使用的代码?

提问于
浏览
31

Coverage工具擅长查找已使用和未使用的代码 . 但是,似乎没有办法只保存或导出使用过的代码 . 即使隐藏未使用的代码也会有所帮助

我正在尝试减少应用程序中的Bootstrap CSS数量;该文件超过7000行 . 获取所用代码的唯一方法是仔细滚动文件,查找绿色部分,然后将该代码复制到新文件 . 这是耗时且不可靠的 .

有不同的方式吗? Chrome 60似乎没有添加此功能 .

2 回答

  • 10

    你可以用木偶戏做到这一点

    (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();
    })();
    
  • 5

    我和拥有此功能的工程师交谈过 . 从Chrome 64开始,仍无法导出覆盖率分析的结果 .

    Star issue #717195帮助团队确定此功能请求的优先级 .

相关问题