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');
}
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.
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]' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With