reactjswebpack-2styled-components

Import fonts to react project with webpack and styled components


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!


Solution

  • 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.