Home > database >  Local fonts with Next.js and Styled Components
Local fonts with Next.js and Styled Components

Time:09-24

I want to add an local font to the project.
I'm using next.js and globalStyles from styled-components.

Here is what I've done so far

import regularFont from "../public/fonts/IRANYekanRegular.ttf";

const GlobalStyle = createGlobalStyle<{ lang?: Languages_type | string }>`
@font-face {
  font-family: "ir";
  src: local("ir"), url(${regularFont}) format("truetype");
}     
 
body,
html {
  margin: 0;
  font-family:"ir ";
}

`;

But with the above code it throws and error that says

./public/fonts/IRANYekanRegular.ttf Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for this binary file)

What am I missing?

CodePudding user response:

In Next.js and React applications you can access public files with the absolute route.

So, in your CSS you can do something like:


const GlobalStyle = createGlobalStyle<{ lang?: Languages_type | string }>`
@font-face {
  font-family: "ir";
  src: local("ir"), url('/fonts/IRANYekanRegular.ttf') format("truetype");
}     
 
body,
html {
  margin: 0;
  font-family:"ir";
}

`;

Notice 2 things:

  • I'm not importing the file
  • I'm using the route after public

Not sure if we can use codesanbox for next, so,

  • Related