How to install custom fonts in Rails 6 and Webpacker (and bootstrap and SASS/SCSS)

Viewed 1156

I am having trouble using local fonts (downloaded from fonts.google.com). [While I might be able to externally reference the font in the example below on Google, I want to try using the font locally, because eventually I am going to be using a different custom font not available on Google.]

I am using Rails 6 (6.0.3.2), along with the gem Webpacker 4 (and the gems bootstrap 4.5 and sass-rails 6).

I have copied fonts to: /app/javascript/fonts/source-sans-pro (source-sans-pro is name of font), and font file inside that I am referencing is: SourceSansPro-Regular.otf

In my application.scss (/app/javascript/src/stylesheets/application.scss), I have the following:

    @font-face {
       font-family: 'Source Sans Pro', sans-serif;
       src: url('/media/fonts/source-sans-pro/SourceSansPro-Regular.otf') format("opentype");
    }

In the application.scss, I am also importing my _custom.scss @import '_custom';

In my _custom.scss (same directory), I have this section of code:

.vs-text {
  color: #fff2eb;
  font-family: "Source Sans Pro", Tahoma, Geneva, Verdana, sans-serif;
}

...and finally, on the application.html.erb, I have this tag: <body class="vs-text">

When I start the app, Webpacker compiles successfully (server logs), but my fonts are not displayed. Inspecting the elements with Chrome developer tools (F12), shows that the correct font-family styling is being attempted, but it isn't my font. I believe that the font family is failing over to a subsequent font in the list.

Any tips on what I am doing wrong?

Thanks, Mark

2 Answers

I am a recent user of Webpack and not a good JS coder yet I managed to get my fonts compiled by Webpack.

Actually in your CSS when you point to your font in "media" folder you are refering to the compiled asset in "public/packs/media" folder.

Though what you want is not to use the data in the public folder, you really want to compile that font so it eventually ends up in this folder.

Then instead of pointing to "/media/fonts/source-sans-pro/SourceSansPro-Regular.otf" you want instead to refer to your font in the javascript folder : "../fonts/source-sans-pro/SourceSansPro-Regular.otf" then you will see the font compiled properly and appear in "public/packs/media" folder.

NB: OTF is not the best compiled font format ( https://creativemarket.com/blog/the-missing-guide-to-font-formats ). You better version your font into WOFF and WOFF2 through this website : https://transfonter.org/

Easiest way to add a font - add a font like this to views/layouts/application.html.erb:

<link href="https://fonts.googleapis.com/css?family=Lato:400,900&display=swap" rel="stylesheet">

inside <head> tag

Related