4
votes

I'm trying to import fonts from a local resource in my react project which uses webpack and styled components. I have a fonts folder with the following code:

import { css } from 'styled-components';
import { fontWeight } from './vars';

export const fontFaces = css`
  @font-face {
    font-family: 'OurFont';
    src: url('/resources/fonts/OurFont-Bold.woff2') format('woff2');
    font-weight: ${fontWeight.bold};
    font-style: normal;
  }
`;

then I have a global styles file with:

import { createGlobalStyle } from 'styled-components';
import { fontFaces } from './fonts';

export const GlobalStyles = createGlobalStyle`
  ${fontFaces}
`;

In my app component I use the ThemeProvider from styled-components like this (left out some code non relevant code here for brevity):

import { ThemeProvider } from 'styled-components';

class App extends React.Component {
render() {
  return (
    <ThemeProvider theme={{ theme }}>
      <GlobalStyles />
      <AppHeader />
      <AppNavigator />       
    </ThemeProvider>
  );
}}

And the relevant code from webpack:

module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: ['babel-loader'],
    },
    {
      test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
      use: [
        {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            limit: 10000,
            mimetype: 'application/font-woff',
          },
        },
      ],
    },

I tried following the advice from this thread but it does not seem to work for me as I get an error in the console which says GET http://localhost:5001/resources/fonts/OurFont-Bold.woff2 net::ERR_ABORTED 404 (Not Found).

Does anyone know what I am doing wrong or if there is another approach? Thanks!

2

2 Answers

6
votes

You can solve this problem by importing the font in your JS and passing it down to your styled components css template tag:

import { css } from 'styled-components';
import { fontWeight } from './vars';

import myFontURL from '../../mypath/fonts/OurFont-Bold.woff2';

export const fontFaces = css`
  @font-face {
    font-family: 'OurFont';
    src: url(${myFontURL}) format('woff2');
    font-weight: ${fontWeight.bold};
    font-style: normal;
  }
`;

Be sure to not use /resources/fonts/OurFont-Bold.woff2, and use a relative path to your current file's directory instead.

1
votes

Facing the same problem and tried the above stated solution, but it doesn't work and i get the error message: Cannot find module '../fonts/Roboto-BlackItalic.ttf'

I'm using typescript so do I need to add some kind of export to be able to use the import statement for that kind of path?

Edit: solved by adding declare module "*.ttf"; to my typings.d.ts file and removing the format("ttf") in src: url(${fontUrl}) format("ttf"); in @font-face