JensM
JensM

Reputation: 143

How to remove most index.ts files from my project

I'm looking to optimize my React folder structure. It looks like this:

- components
  - Header
    - Header.tsx
    - Header.styles.ts
    - index.ts

The index.ts is just there to allow me to import the Header component with import { Header} from "components/Header. This works because I'm using babel-plugin-module-resolver. Now, since my folder name is always the same as the main file name inside my components folder, I would like to be able to import the header with import { Header } from "components" and have a Babel plugin resolve this to import { Header } from "components/Header/Header". This would mean I could remove the index.ts

Which Babel plugin can do this?

I'm already using babel-plugin-module-resolver to resolve the components folder. My problem is that i'm also using TypeScript so how do I tell the TypeScript compiler that this module is being resolved like this?

Please help me out. Thanks!

Upvotes: 2

Views: 1082

Answers (1)

Zachary Haber
Zachary Haber

Reputation: 11037

You should be able to just have your index.ts in your components take care of that normally. I don't think that this has anything to do with babel-plugin-module-resolver, it's just how index.ts/js files work in general. https://alligator.io/react/index-js-public-interfaces/

You should be able to get what you are looking for by doing the following in your index.ts file in your component directory:

You import your Header component and then directly export it.

import {Header} from './Header/Header'
export Header

Or you might be able to do a symmetrical export depending on your setup:

export {Header} from './Header/Header'

Upvotes: 1

Related Questions