8

I have an Angular CLI app and I'm using @import '~@angular/material/theming'; in the global styles.scss. I also have a component where I would like to define a css class in that component's .scss file that uses some of the Angular Material typography:

@import '~@angular/material/theming';

$config: mat-typography-config();

.myClass {
  font-size: mat-font-size($config, title);
  font-weight: bold;
}

By importing ~@angular/material/theming more than once in my application, will it include that css more than once and bloat my payload? Or is the Angular CLI compiler smart enough to handle this?

adam0101
  • 29,096
  • 21
  • 96
  • 174
  • "Angular CSS compiler" - the purging would be done by another component. The conductor for all the transformations in Angular CLI is, I believe, Webpack, but the latest versions of Angular hide its config from you. You likely want to include [this](https://github.com/FullHuman/purgecss) or its predecessor, and I don't think it is included by default. It's a pretty pickle. You can follow [this issue](https://github.com/FullHuman/purgecss/issues/96). Possible duplicate: [Can angular-cli remove unused css?](https://stackoverflow.com/questions/40330938/can-angular-cli-remove-unused-css) – Amadan Jan 07 '19 at 04:33
  • @Amadan, so my question was if `@import` will duplicate the code. Are saying that it will since you're suggesting the use of a utility that will remove duplicate code? Either way, I don't think it's a duplicate question since I never asked how to remove duplicate css, only if it would be duplicated in the first place. – adam0101 Jan 07 '19 at 04:36
  • Yes. Also, see [this](https://github.com/angular/angular-cli/issues/8431). (As for not being a duplicate, look at it this way: if I see someone giving a class about how not to get eaten by hungry bears in winter, I don't think I need to ask if bears are dangerous :P ) – Amadan Jan 07 '19 at 04:38

1 Answers1

2

If you're importing the same CSS into multiple components, then yes the CSS will be duplicated, but each time it will be scoped to that component.

For example if you have the following...

product-list.component.css:

@import '../../foo.css';
...

top-bar.component.css:

@import '../../foo.css';
...

../../foo.css:

a { color: red; }

Your css output in the tag will look something like this:

<style>
   a[_ngcontent-gna-c48] { color: red; }
   ...
</style>

<style>
   a[_ngcontent-gna-c50] { color: red; }
   ...
</style>

Here's a full StackBlitz based on Angular's Getting Started example project.

Wedge
  • 31
  • 4