无法导入node_modules中已存在的react-image-gallery库如何解决
报错Could not find a declaration file for module 'react-image-gallery'是TypeScript检测模块类型时,未找到react-image-gallery对应类型声明文件导致,该库本身未内置TS类型声明,按以下步骤配置即可解决:
优先方案:安装社区维护的类型包
执行以下命令安装社区维护的类型定义依赖:
yarn add -D @types/react-image-gallery
安装完成后重启TypeScript服务即可消除报错:VS Code用户可按快捷键Ctrl+Shift+P(Windows)/Cmd+Shift+P(Mac)调出命令面板,输入Restart TS Server执行重启。
备用方案:手动编写模块声明
如果安装@types包提示404,或是版本不匹配无法兼容,可手动添加模块声明:
- 在项目
src目录下(即tsconfig.json中include配置覆盖的路径内),新建后缀为.d.ts的声明文件,例如命名为modules.d.ts - 在文件中添加以下内容,即可让TS跳过该模块的类型校验:
declare module 'react-image-gallery';
如果需要基础类型提示,可以扩展声明内容:
declare module 'react-image-gallery' { import type { FC } from 'react'; export interface ImageGalleryItem { original: string; thumbnail?: string; description?: string; [key: string]: any; } export interface ImageGalleryProps { items: ImageGalleryItem[]; [key: string]: any; } const ImageGallery: FC<ImageGalleryProps>; export default ImageGallery; }
- 保存文件后重启TS服务即可生效。
使用注意
该组件的样式文件需要单独引入,否则会出现样式错乱问题:
import ImageGallery from 'react-image-gallery'; // 引入组件核心样式 import 'react-image-gallery/styles/css/image-gallery.css';
问题参考截图

内容的提问来源于stack exchange,提问作者Flippingflop
相关产品推荐
相关产品推荐

