React Cannot find module - ttf, otf fonts
Asked Answered
J

3

20

I'm trying to load local font like the code below but I keep getting Cannot find module '@/landing/fonts/Gotham-Bold.ttf' error and have no idea what is really wrong this path.

my folder structure looks like this, and the code I'm working on is LandingPage.tsx

enter image description here

import { createGlobalStyle } from 'styled-components';
import font from './fonts/Gotham-Bold.ttf'

const Gotham = createGlobalStyle`
  @font-face {
    font-family: 'Gotham';
    font-style: normal;
    font-weight: bold;
    src:
      url(${font}) format('truetype'),
  }
`
Jubilant answered 28/2, 2019 at 10:14 Comment(2)
Did you manage to get this working?Tectrix
This is what worked for me. Import like this... src: url('../assets/fonts/gilroy/gilroy.woff2') format('woff2');Cordeiro
T
35

Know this a bit old but it could be a problem with Typescript. When using a font file with Typescript you have to declare the formats as a module.

For that you can create a fonts.d.ts file and add the following code inside it:

declare module '*.ttf';

That way Typescript will know how to handle .ttf files. You also will need a appropriate Webpack loader.

Threequarter answered 3/9, 2020 at 15:31 Comment(2)
This throws Invalid module name in augmentation, module '*.ttf' cannot be found. for me.Waltner
Just to clarify, cause it took me a while to figure our where to put the file, it should go in the very same fonts folder that you create to store the .ttf files. In my case at least, this solved the whole issue, thank you!Bayne
U
4

We need to add a declaration file, and tell Typescript that .ttf files can be imported as modules. I did so as follows:

// file: src/assets/fonts/fonts.d.ts

declare module "*.ttf";

That file(fonts.d.ts) must be near with font file

Underpants answered 13/1, 2024 at 22:58 Comment(0)
R
-1

According to your folder structure LandingPages.tsx is inside pages folder. The pages folder is a sibling of the fonts folder. You need to traverse to fonts folder from inside of pages folder.

The correct path will be '.././fonts/Gotham-Bold.ttf'

You need to move one level up (..) and then go to the fonts folder.

Let me know if this fixes your issue.

Reticle answered 28/2, 2019 at 11:8 Comment(2)
this doesn't work. and react will display an error 'Cannot find module'Lindahl
Could it be that you have the dots in the reverse order? I'm pretty sure it should go like ./../fonts/etc.ttfBayne

© 2022 - 2025 — McMap. All rights reserved.