Back to Posts

Rails 5.1, Yarn, Webfonts and Sass

If you are using Rails 5.1 along with Yarn to manage your assets and are using the default configuration you might have ran into issues using your font's on production. In this post, I will show you how I got around this issue. I will be using Font-Awesome to demonstrate.

Add fonts to be precompiled

Open up config/initializers/assets.rb and add the following line.

1
Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/

Adding font to application.scss

Change path to font location

In the case of Font-Awesome, it has a variable ($fa-font-path) defined for the font path. This can be found at node_modules/font-awesome/scss/_variables.scss You will want to override this variable to point to the appropiate path so it can be found in production.

1
2
// No need to add assets folder in the path as we are using sass-rails helpers
$fa-font-path: "font-awesome/fonts";

Because the origin variable has the !default flag, the variable created above will need to be placed before loading Font-Awesome.

1
2
$fa-font-path: "font-awesome/fonts";
@import "font-awesome/scss/font-awesome";

Override @font-face

Now you will want to override the existing @font-face to use asset helpers provided by the sass-rails gem. You will want to place the newly created @font-face definition after the library.

1
2
3
4
5
6
7
8
9
10
11
12
13
// We changed 'url' to the 'font-url' asset helper
@font-face {
  font-family: 'FontAwesome';
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
//  src: font-url('#{$fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts
  font-weight: normal;
  font-style: normal;
}

If everything was successful, your font's should now be displaying correctly on production.