Update: The Code Coverage feature is now shipping with standard Chrome. If you’ve updated to the latest version, there’s no need to use Canary!
What does it do?
Code coverage lets you run your web app, and for each JS/CSS file, see which lines of code ran and which didn’t.
Here, I ran a simple static web page- and Chrome generated this breakdown of the CSS and JS files that were present on the page. The bars on the right show the relative size of each file, red representing unused code, and green showing code that ran.
Recording code coverage works similarly to the devtools timeline- you hit record and then interact with your site normally. When you’re done, Chrome does some calculations and generates the readout. Here, I was curious about how much unused CSS was on the site, so I navigated to the various sub-pages to make sure that I hit every css “code path”. Sure enough- there’s a lot of room for improvement here, as 97% of the css on my site was unused!
Chrome also lets you drill down into an individual file’s code coverage. Here, the red/green bar on the left shows which specific lines ran and which didn’t. Note that when inspecting minified files, you can press the button in the lower-left corner of file to “prettify” the code.
Why is it useful?
When working on a complex or long-term project, it is easy to accumulate dead code. If you’re using webpack or another JS build system, there are tools for preventing most dead JS code from making it to production. But for CSS, it can be a bit trickier to do this. Having this coverage tool in Chrome is a great way to get a quick overview of how much extra code you’re shipping, and which files to optimize.
How to get it?
Download Chrome Canary or wait a few weeks for it to reach regular Chrome.
It’s tough to keep up-to-date on front-end dev. Join our weekly mailing list to learn about new tools, libraries and best practices that will help you build better apps:
Plug: LogRocket, a DVR for web apps
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.