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

Find out how to fix the TypeScript "Cannot find module" error when importing local fonts

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.


Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.