How to fix "cannot find module or its corresponding type declarations" error in Svelte 5

Saturday, December 21, 2024
2 min read

When working with Svelte 5 and TypeScript, you might have seen the "Cannot find module or its corresponding type declarations" error. This is a common issue when using Vite for development, particularly when trying to import Svelte components.

Why does ‘cannot find module or its corresponding type declarations’ error occur?

This error typically occurs when TypeScript can’t locate your module’s type definitions. Let’s look at two common import scenarios:

Traditional import

<script>
  import Counter from './lib/Counter.svelte'
</script>

<Counter />

Alias Import (Fails without proper configuration):

<script>
  import Counter from '$lib/Counter.svelte'
</script>

<Counter />

How to fix the ‘cannot find module or its corresponding type declarations’ error

There are two simple steps to resolve this error:

1. Create type declarations

First, create a svelte.d.ts file in your src directory:

declare module "*.svelte"

This tells TypeScript to recognize all .svelte files as valid modules.

2. Configure TypeScript

Update your tsconfig.json to use project references:

{{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ],
  "include": ["src"], // set inlude option here to specify the source directory
}}

How it works

The svelte.d.ts file provides type declarations for Svelte files, allowing TypeScript to recognize them as valid modules.

Conclusion

By adding a simple type declaration file and properly configuring TypeScript project references, you can resolve the “Cannot find module” error in your Svelte 5 project.