środa, 23 stycznia 2019

How to fix: Webpack file-loader corrupting fonts

The problem

Recently I've been forking on a fairly simple React / Webpack application, built with newest CRA (https://facebook.github.io/create-react-app/).
Everything was fine in the development but when I built a production package, I started noticing strange warnings in dev tools console. All of them concerned fonts loading, for example:

Failed to decode downloaded font
OTS parsing error: incorrect entrySelector for table directory
OTS parsing error: incorrect file size in WOFF header

After short investigation it became apparent that file-loader is not able to handle WOFF or TTF fonts correctly, returning empty content.


The solution

Webpack allows for configuration of loaders per file name pattern. Therefore it's fairly easy to switch fonts loading to use URL loader instead of file loader. Just add following right before generic file loader kicks in (typically - last entry  in module/rules/oneOf):

{
 test: [/\.woff$/,/\.ttf$/],

  loader: require.resolve('url-loader'),
options: { limit: 150000,
mimetype : 'application/font-woff',
name: 'file?name=static/media/[name].[hash:8].[ext]',
}, },

Now all of your fonts will be served as embedded data URLs. This obviously will make resulting package bigger and will prevent separate caching of fonts - it's a tradeof. Also please make sure you set appropriate limit so that all "offending" fonts are captured!

Brak komentarzy: