How to Fix "Cannot Find Module" Error When Importing Fonts With TypeScript?

If you're trying to import fonts into your typescript project and getting the following error:

Cannot find module 'xyz.woff'

Then you probably need to declare the font file type(s) as modules so TypeScript can recognize them for import.

How to Declare Files as Modules in TypeScript?

Create a .d.ts file (for e.g. fonts.d.ts) and add your file definitions in there. For example:

declare module '*.woff';
declare module '*.woff2';

This would tell TypeScript that the declared font types are valid import modules.

How to Make TypeScript Recognize Your Definition Files?

Configure the path to your *.d.ts file(s) in your TypeScript configuration file (tsconfig.json). You can do that in the following ways:

Using include:

Generally, a good idea is to put all your custom type definitions into one folder, for example, ./src/types. You could then include these definitions by using the include option in your tsconfig.json file as follows:

{
    "include": [
        "src/**/*",
    ]
}

The ** means recursively match any sub-directory, and the * at the end matches all supported file extensions (which includes the *.d.ts files by default).

Using typeRoots:

By default, TypeScript includes all visible @types packages (for e.g. from node_modules/@types, etc.) into your compilation. You can change this behavior by specifying typeRoots (in your tsconfig.json file) like so:

{
    "compilerOptions": {
        "typeRoots" : ["src/types"]
    }
}

This will include all packages in the src/types folder and exclude node_modules/@types. To include node_modules/@types as well in typeRoots, you could re-write the above as:

{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@types", "src/types"]
    }
}

Why Does the "Cannot find module" Error Happen When Loading Fonts?

It happens because of module resolution. You need to declare the font file formats as modules so that TypeScript can understand and parse them correctly. TypeScript relies on definition files (*.d.ts) to figure out what an import refers to. When that information is missing, you get the "Cannot find module" error.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.