SvelteKit中桶文件index.ts抛出TypeError:找不到模块
问题描述
- 操作场景:在SvelteKit中尝试通过单个桶文件重新导出图标
- 遇到的错误:
index.ts中提示:Cannot find module './AcademicCap.svelte' or its corresponding type declarations. - 文件夹结构:
icons/ ├─ AcademicCap.svelte ├─ index.ts index.ts代码:export { default as AcademicCap } from "./AcademicCap.svelte";- 补充:
AcademicCap.svelte为SVG图标组件代码
解决方案
这个错误的核心是TypeScript无法识别.svelte后缀的文件模块类型,按以下步骤解决:
添加Svelte类型声明文件
在项目根目录或icons文件夹下创建types.d.ts文件,写入:declare module '*.svelte' { import type { ComponentType } from 'svelte'; const component: ComponentType; export default component; }同时确保
tsconfig.json的include数组包含**/*.d.ts,保证TypeScript能读取到这个声明文件。检查TypeScript配置
打开tsconfig.json,确认compilerOptions里有以下配置:{ "compilerOptions": { "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "esModuleInterop": true } }SvelteKit默认配置一般包含这些,但如果手动修改过配置,需要确认配置项正确。
调整导出写法(可选)
可以换一种导出写法,确保TypeScript正确识别:import AcademicCap from './AcademicCap.svelte'; export { AcademicCap };重启开发服务器
修改完成后重启SvelteKit开发服务器,让TypeScript重新编译类型声明。
内容的提问来源于stack exchange,提问作者Lorik
相关产品推荐
相关产品推荐

