React TypeScript跨文件夹导入组件报错:无法找到模块或类型声明
组件导入报错:Cannot find module './components/' 问题排查与解决
问题背景
我的文件夹结构如下:
- 根目录
- Chat.tsx
- components/
- MessageList.tsx
- MessageSent.tsx
我想在Chat.tsx中导入这两个组件,写了如下代码:
// Chat.tsx import React from 'react' import {MessageList, MessageSent} from "./components/" type Props = {} const Chat= (props: Props) => { return ( <div>Chat</div> ) } export default Chat
MessageSent.tsx的代码(MessageList.tsx结构类似,仅组件名称不同):
// MessageSent.tsx import React from 'react' type Props = {} const MessageList = (props: Props) => { return ( <div>MessageList</div> ) } export default MessageList
但运行时一直报错:Cannot find module './components/' or its corresponding type declarations. 试过各种路径甚至完整路径,都没解决。
报错原因
- 目录导入缺少入口文件:直接导入
./components/这种目录路径,要求该目录下必须有index.ts或index.tsx作为入口文件,用来统一导出目录内的组件,否则React/Node无法识别这个目录作为模块。 - 导出与导入语法不匹配:你的组件用的是
export default(默认导出),但导入时用的是{MessageList, MessageSent}这种命名导入语法,两者不兼容。 - 组件名与文件名不匹配:MessageSent.tsx里定义的组件名是
MessageList,和文件名完全不符,这会导致导入时组件逻辑混乱。
解决办法
办法一:直接导入单个组件文件(最快捷)
修改Chat.tsx的导入语句,明确指定每个组件的具体文件路径:
// Chat.tsx import React from 'react' // 直接导入对应文件,默认导出的组件可以自定义名称(这里用组件原名) import MessageList from "./components/MessageList" import MessageSent from "./components/MessageSent" type Props = {} const Chat= (props: Props) => { return ( <div> <MessageList /> <MessageSent /> </div> ) } export default Chat
同时必须修正MessageSent.tsx的组件名错误:
// MessageSent.tsx import React from 'react' type Props = {} // 组件名要和文件名、功能对应 const MessageSent = (props: Props) => { return ( <div>MessageSent</div> ) } export default MessageSent
办法二:创建目录入口文件(适合组件较多的场景)
在components文件夹下新建index.ts文件,统一导出所有组件:
// components/index.ts // 将默认导出的组件转为命名导出 export { default as MessageList } from './MessageList' export { default as MessageSent } from './MessageSent'
之后就可以在Chat.tsx中使用你原来的导入方式了:
// Chat.tsx import React from 'react' import { MessageList, MessageSent } from "./components/" // 后续正常使用组件即可
同样要先修正MessageSent.tsx的组件名错误。
内容的提问来源于stack exchange,提问作者TheCulprit
相关产品推荐
相关产品推荐

