Import fonts to react project with webpack and styled components
Asked Answered
N

3

5

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!

Nazarene answered 6/3, 2019 at 20:29 Comment(0)
M
7

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.

Mail answered 6/3, 2019 at 20:41 Comment(2)
That seems to work :) Quick follow up question: Do you know if this will work for a production build?Nazarene
Yes, it definitely should – unless you use some kind of CDN, then you need to configure webpack specifically for that.Mail
A
3

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

Assyrian answered 7/3, 2019 at 14:2 Comment(2)
Basically TS doesn't deal with CSS. I solved by just adding a directory copy to my TS build commandLecythus
In my case, the trick was to remove the format("ttf").Vapory
A
0

You can solve your problem creating a file falename.css(in my case was font.css) and the @font-face how is below:

@font-face {
    font-family: 'inter-black';
    src: url('../assets/font/Inter-Black.ttf');
    font-display: swap;
}
@font-face {
    font-family: 'inter-light';
    src: url('../assets/font/Inter-Light.ttf');
    font-display: swap;
}

then you will import it into the your project index.js importation print of font.css

After this you can use the code in styled-component

export const MainTitle = styled.h1`
    font-family: 'inter-black';
`;
Augite answered 12/1, 2023 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.