Does using @import more than once duplicate css?

Viewed 1085

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?

1 Answers

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.

Related