Self-hosting Google Fonts in Angular web projects
- Posted by Muthukumar Dharmar
- Categories Angular, Tips & Tricks
- Date August 23, 2020
In this article we will see how to self host and configure google fonts inside our angular projects. Of course, CDN’s are great solutions, but still there are cases where we may need to self host the fonts. This will also avoid some unknown surprises related to browser’s Content Security Policies.
Below are few steps that I use to self-host google fonts along with my angular applications.
Let's download the fonts
For this demonstration, I’m using a project created using the Angular CLI tool. Let’s run the project using ng s -o command.
Now go to developer tools -> Network Tab. Then click on CSS in filter settings and select the http request https://fonts.googleapis.com/css.
Click on preview tab and copy the CSS content to VS code or to your favorite text editor.
Now we have to download the font files, for that click on the fonts filter in the settings and double click on the google font files and download it to you local machine.
If required download all the font files referred in the CSS, otherwise we have to simply remove those font-face segments before using it.
Now we have downloaded the necessary assets to self-host google fonts from our angular web application.
Project level changes
Let’s do the necessary changes in our project.
- Create a folder named fonts inside the assets folder in our project.
- Copy and place the font files (.woff2) inside our local fonts folder.
- Save the CSS content that we downloaded in to a file named font.css
- Now our assets folder should look like the image in the right side
In this demo, I’m using the chrome browser where it supports the woff2 font files, I you need support for legacy browsers. You should download the fonts as .ttf files and update the font.css accordingly.
Another solution
If you are not interested in doing this manually, then there great ‘google-webfonts-helper that assists in creating the css and provides fonts compatible with all browsers.
Try this:
- Navigate to google-webfonts-helper
- Search and select font family
- Select the character set
- Select required styles
- Copy the CSS and download the fonts
Then just paste the font files and css file as we did already.
Hope this is helpful 🙂
One last thing, don’t forget to replace the <link> or @import references to our local font.css file
Final Demo
Tag:fonts, fonts as assets, google fonts
Previous post