CSS Coverage on Angular App
What’s CSS coverage ?
https://developers.google.com/web/tools/chrome-devtools/coverage
Why CSS coverage ?
Advantages I want:
- Dead styles elimination
- However component oriented frameworks(e.g. Angular, Vue.js) have function to emulate scoped CSS
- Visualize how many styles are tested using browser-automation tools(e.g. Karma) and coverage service(e.g. Coverall)
Let’s measure Angular app!
It seems working well.
It’s not !
First, I created a simple Angular app via ng new
and measured CSS coverage for this:
Ok, My Chrome captured JavaScript coverage. However where’s CSS ?
The above example was served via ng serve
. So next, I tried via ng build --prod; http-server
.
I did it!
Wait. Devtool indicated only the global(external) CSS. There are no coverage of components’ styles.
It seems that Chromium can’t measure inline styles via generated dynamically.
OK, I got it. If that’s what you want static CSS files, I’ll just do it!
Finally, I tweak the example with ng add @nguniversal/express-engine
. Yes, we can use SSR to provide CSS before rendering.
But it’s not enough. @angular/platform-server
creates CSS styles on Node.js but they're just inline-styles. I want .css files for <link>
. So I wrote an interceptor to convert <style>
elements generated by platform-server to <link rel="stylesheet">
.
Conclusion
- Measuring CSS coverage of Angular app is so tough.
- Chrome can’t measure coverage of
<style>
generated dynamically. - It’s not only for Angular App but also for other libraries(e.g. React + styled-components).
- If you want to measure, you should provide static CSS contents (e.g.
@angular/platform-server
)