Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom fonts in Rails 6 with Webpack

For my newly started Rails 6 application I want to have a set of customs fonts. My setup looks like this:

# app/assets/stylesheets/my-font.sass

@font-face
  font-family: 'my-font'
  src: url('fonts/my-font.eot') format('embedded-opentype'), url('fonts/my-font.woff') format('woff'), url('fonts/my-font.ttf') format('truetype'), url('fonts/my-font.svg#my-font') format('svg')
  font-weight: 400
  font-style: normal

And then under app/assets/stylesheets/fonts I have all 4 files referenced in the sass file.

My application.sass has the following import: @import 'my-font'.

When I run rails assets:precompile it also puts all 4 files with suffixed version (e.g. my-font-7384658374658237465837246587263458.eot) in the public directory.

BUT, when I run the application the browser is looking for a file in the root directory called my-font.eot, which of course isn't there and 404s. This looks definitely like a configuration problem to me, but where I have no idea. Any help would be much appreciated.

like image 264
Severin Avatar asked Aug 21 '19 12:08

Severin


People also ask

How do I import a font into Webpack?

If you have some local font files of your own, place them in a font directory within src and reference them within . style. scss using @font-face as you normally would—webpack will see that you're referencing a font file and run it through the file-loader like it did with Font Awesome and Google Fonts.

Where do I put laravel font files?

How do I import fonts into laravel? mix. js // resources/assets/fonts directory contains our fonts file // copyDirectory helps to copy all the files with directory structure // then we can import our custom fonts as in above mentioned method in blade or css file mix.


1 Answers

If you have the fonts inside /assets/ then use the asset-url helper.

src: asset-url('fonts/my-font.eot') format('embedded-opentype'),
     asset-url('fonts/my-font.woff') format('woff'),
     asset-url('fonts/my-font.ttf') format('truetype'),
     asset-url('fonts/my-font.svg#my-font') format('svg')

That way Sprockets will change "fonts/my-font.xxx" to the filename with the digest.

Personally I don't like to put fonts on the assets pipeline since they are probably not changing and only slows down your precompilation time, so I put them in public:

/public/fonts/my-font.eot
/public/fonts/my-font.woff
...ect...

And just use your original css code.

(This has nothing to do with webpack or webpacker)

like image 104
arieljuod Avatar answered Oct 16 '22 12:10

arieljuod