Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fonts not found with nested routes in react-router

I'm using React, React-Router and Webpack (with webpack-dev-server) and I'm having trouble loading custom fonts on nested routes.

Everything works fine on my shallow routes like /user, /group, etc., but when I have a nested route like /group/user, the custom fonts don't get loaded (404 error).

The Webpack build puts all the fonts in the root level as expected (with filenames like 7f690e503a254e0b8349aec0177e07aa.ttf), and when showing a route like /user, the fonts are loaded properly.

However, when in a nested route like /group/user, the browser tries to load the fonts from a URL like /group/7f690e503a254e0b8349aec0177e07aa.ttf, which doesn't exist.

I think that somewhere the font is assumed to be a relative path, but I don't know where.

How can I make the font paths be absolute paths rather than relative? Or is there another way to fix this?

Not sure if it matters, but I've defined my fonts as shown below in my styles.less file:

// Main font(s)
@font-face {
  font-family: 'Lato-Regular';
  src: url('../fonts/Lato-Regular.ttf') format('truetype');
}
like image 596
MindJuice Avatar asked Dec 29 '15 00:12

MindJuice


2 Answers

In this case a possible solution is to add the base element to your pages. The base element allows you to specify a base URL to be used throughout the document for relative URL addresses. For example setting:

<base href="http://www.youdomain.com/">

then you know that all relative paths should be relative to the root of your domain.

like image 122
Davide Ungari Avatar answered Oct 13 '22 03:10

Davide Ungari


I had the same problem using webpack and react router 4. I solved it by switching from file-loader to url-loader in webpack.config.json.

Working Module - Loader:

{ test: /\.(otf|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, loader: 'url-loader?name=./Scripts/dist/[name].[ext]' }
like image 44
Ogglas Avatar answered Oct 13 '22 03:10

Ogglas