1

I have the following folder structure

enter image description here

I want to import both MessageList.tsx and MessageSent.tsx inside my 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
import React from 'react'

type Props = {}

const MessageList = (props: Props) => {
  return (
    <div>MessageList</div>
  )
}

export default MessageList

MessageList.tsx is similar to MessageSent,tsx, only the name of the components is different

However, when I try to do the import of these two components {MessageList, MessageSent} I get the following error:

** Cannot find module './components/' or its corresponding type declarations.**

Why is that?

Tried different paths besides "./components/", even with full path.

1
  • You need index.ts with exports from both MessageList.tsx and MessageSent.tsx file in the components folder Commented Nov 22, 2022 at 16:25

3 Answers 3

2

You can either import the components one by one

import MessageSent from "./components/MessageSent"
import MessageList from "./components/MessageList"

or create an index directory file (index.ts)

import MessageSent from './MessageSent'
import MessageList from './MessageList'
export { MessageSent, MessageList }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This seems to be working. I believe the only solution so I don't have to create an index.ts file inside the components folder is to import them one by one. Why is this index.ts file required and you simply can't import them directly?
@SpamSpasmodium Import keyword will look for explicit specified file or index file in a folder. So, the code you write will look for components/index.ts, but since you doesn't have that file, that doesn't work.
1

To be able to import from components you need index.ts file in components folder.

// index.ts
export * from './MessageList';
export * from './MessageSent';

Comments

1

Add a new file named index.ts inside your components folder
Then write this in the index.ts

export * from './MessageList.tsx';
export * from './MessageSent.tsx';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.