npm monorepo导入Svelte组件报错:找不到模块或类型声明
Monorepo中TypeScript无法识别Svelte组件模块的问题解决
问题原因
- TypeScript默认不解析
.svelte文件:shared_library的tsconfig.json里include数组仅包含**/*.ts,未纳入.svelte文件,导致TypeScript无法识别./ui/Button.svelte模块。 - 缺少Svelte类型支持配置:TypeScript不知道如何处理Svelte文件的类型逻辑,即便存在
Button.d.ts,也无法自动关联到对应的.svelte模块。
解决步骤
1. 修改shared_library的tsconfig.json
更新配置,让TypeScript识别.svelte文件并加载Svelte基础类型:
{ "compilerOptions": { // 保留原有配置,新增以下项 "types": ["svelte"], "resolveJsonModule": true, "moduleResolution": "node", "extensions": [".ts", ".js", ".svelte"] }, "include": [ "**/*.ts", "**/*.svelte" // 添加这行,纳入所有svelte文件 ] }
2. 确认Button.d.ts的正确性
确保类型声明文件能正确映射Svelte组件,示例内容如下:
declare module './ui/Button.svelte' { import type { ComponentType } from 'svelte'; // 按需定义组件Props类型 interface ButtonProps { label?: string; disabled?: boolean; } const Button: ComponentType<ButtonProps>; export default Button; }
如果是自动生成的类型文件,检查生成路径是否与组件文件对应。
3. 检查components目录的package.json
确认这个命名空间的package.json能正确暴露入口和类型:
{ "name": "@shared/components", "main": "./index.ts", "types": "./index.ts", "type": "module" }
4. 刷新依赖与TypeScript服务
在shared_library目录下重新安装依赖:
npm install
然后重启编辑器的TypeScript语言服务(比如VS Code可按Ctrl+Shift+P,选择"TypeScript: Restart TS Server"),让配置生效。
内容的提问来源于stack exchange,提问作者jeff
相关产品推荐
相关产品推荐

