Angular 9: SCSS Import from fonts.google.com does not work in a production mode

Viewed 777

I am importing a font in Angular 9 app style.scss using the following syntax:

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap');

This works when I run ng serve. However, the import does not seem to work when the Angular bundle is deployed in the production mode. The production bundle makes no attempt to load this font - there is no network request. Further there are no errors in the Chrome console.

I have locally installed fonts that do work - so I suspect this has something to do with third-party hosted fonts:

@font-face {
  font-family: Korolev;
  font-weight: 600;
  font-style: normal;
  src: url('assets/fonts/korolev-medium-webfont.ttf');
}

Tracing down the error, it is related to something called injectStylesIntoStyleTag.js, from a Webpack style-loader. This seems to do the trick when ng serve is run in the development mode, as we can see a request initiated from the script that creates <style> in the head that loads the font. However, when run in the production mode either the mechanism to load fonts is different or it does not seem to kick in.

network log entry

  • Should SCSS imports from third party work normally in Angular production mode?

  • If import for third party fonts is not recommended, what is the preferred mechanism to use third party fonts in stylesheets?

1 Answers

I had the same issue and I just resolved it now by digging into this angular's issue on their github :

I actually had this issue because my @import statement pulling in the google font was not being rendered as the first line in my compiled css file. I recently upgraded my version of Angular. Not sure why this change happened, but I solved for my case by breaking my font imports into a scss partial file and imported THAT partial file before anything else. The result is that my font @imports are the first line of my styles.css.

TLDR;
@import statements have to be at the top of the compiled css file or they will be ignored.

To do so, I created a file font.scss which contains all my @import like this :

@import url('https://fonts.googleapis.com/css2?family=Satisfy&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Patrick+Hand&display=swap');
// [...]

And then you need to update your angular.json to load this file first :

...
"styles": [
    "src/assets/scss/fonts.scss",
    "./node_modules/@angular/material/prebuilt-themes/purple-green.css",
    "src/styles.scss"
],
...
Related