ś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!

wtorek, 22 stycznia 2019

REST API cook book

Introduction


Recently I've stumbled upon an interesting site - REST Cook Book. As nowadays almost everyone develops RESTful APIs and there is a great deal of controversy regarding how to design it properly (say: singular vs plural nouns or collections range query) I decided to take a look at the "recipes" Author serves.

The recipes


First of all, the site is NOT a REST API design guide. Instead, Author decided to write a bunch of short articles concerning some interesting pieces of frequently asked questions. Second of all, Author seems to be focused on HATEOAS (Hypertext As The Engine Of Application State) which differs a bit from "JSON with RPC" style as commonly found in modern Java web applications. The most important difference is that HATEOAS does not care so much about URL structure, as each possible operation for a resource (in other words - possible transition from current state) is returned in form of link / rel / href.
Nevertheless it's an interesting read. Typically authors write a lot about the basics - like mentioned singular vs plurals or how to use basic HTTP methods. Here, we get recipes concerning such rarely discussed aspects as:

  • collection pagination - with link rel = next / first / last 
  • discovering supported HTTP methods with "OPTIONS" 
  • implementing asynchronous operations using 202 "ACCEPTED"
There is also a lot of discussion under almost every recipe, which is very resourceful.