Svelte项目中.ts文件导入.svelte模块触发TS2307错误的排查求助
I've run into this exact issue before—TypeScript has no problem resolving Svelte components from other Svelte files, but throws a fit when you try to import them from .ts files. Let's walk through the fixes step by step:
1. Add a Type Declaration for Svelte Files
TypeScript doesn't natively recognize .svelte modules, so we need to explicitly tell it how to handle them.
Create a new file at src/types/svelte.d.ts (create the types folder if it doesn't exist) with this content:
declare module '*.svelte' { import type { Component } from 'svelte'; const component: Component; export default component; }
This snippet tells TypeScript that any file ending in .svelte exports a valid Svelte Component.
2. Ensure Type Declarations Are Included in tsconfig
Double-check your tsconfig.json's include array covers the new type file. Your current include looks like this:
"include": ["src/**/*", "**/*.config.js"]
Since src/types/svelte.d.ts falls under src/**/*, it should already be picked up automatically. If you placed the type file in a root-level types folder instead, add "types/**/*" to the include array to ensure it's processed.
3. Verify Dependencies and Configuration
Make sure you have all required dependencies installed (you might already have these, but it's worth confirming):
npm install svelte typescript @tsconfig/svelte svelte-preprocess --save-dev
Your Rollup config looks solid, but just confirm that the svelte plugin is correctly using svelte-preprocess (which you've already set up) — this ensures Svelte files are processed properly before Rollup handles your TypeScript code.
4. Clear Caches and Restart Your Editor
Code editors like VSCode often cache old TypeScript configuration, which can cause lingering errors even after you fix the setup. Try these steps:
- Run
npm clean-installto refresh your dependencies and clear npm's cache - Fully restart your code editor
- For VSCode users: Open the command palette (
Ctrl/Cmd + Shift + P) and runTypeScript: Reload Projectto force the editor to pick up new type definitions
5. Double-Check tsconfig Extends
Your tsconfig.json extends @tsconfig/svelte/tsconfig.json, which sets up sensible defaults for Svelte + TypeScript. Just confirm none of your custom compilerOptions are overriding critical settings—your current config (like strict: true) is totally fine and shouldn't cause conflicts.
After working through these steps, TypeScript should recognize your .svelte imports in .ts files without throwing the TS2307 error.
内容的提问来源于stack exchange,提问作者Crocsx

