JavaScript index-naming-hell, what is it and how to avoid it

I used to fall into the same trap…

screenshot of Visusal Studio Code with many index.tsx files open
Look at all those index files

This is how it looks like in the explorer

This works great and in practice it’s easy to use. You can just do

import MyComponent from './components/MyComponent

but when you are editing them in your editor it’s ugly and takes up too much space. It also wrecks quick file navigation since all your files are named… guess what – index.

In this case it’s fine to add some redundancy. If your component is called BirthdayItem, then feel free to rename all your files to BirthdayItem with the proper extension then create an index file that exports your component. So you don’t need to

import MyComponent from './components/MyComponent/MyComponent

Let’s see how it looks in action:

A lot better, now you can actually see what you are editing
Explorer is clean as well

As you can see both the open editors and explorer is a lot more readable. Quick file search also reacts better and easier to find what you are looking for.

Now let’s talk about Intellisense. Whenever I type BirthdayList, VS Code wants to import it from ./components/BirthdayList/BirthdayList. Before the restructure it imported it from the directory like this ./components/BirthdayList. You can clearly see that the latter is the better one. You might think about using the following code and you will get the bad result – just like me.

export { default } from "./BirthdayList";

How do we fix this? In my codebases I try to avoid export default as much as possible. So you can either do it by importing then reexporting as default, like this:

import BirthdayList from "./BirthdayList";
export default BirthdayList;

But as I said, I’d rather avoid export default at all costs:

import BirthdayList from "./BirthdayList";
export { BirthdayList };

This way you will get awesome autocompletion and auto imports without the filename.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s