How to use index.js in project?

Viewed 760

I have the following project structure:

/app
   /components
      /TextInputs
         SearchInput.js
         TextInput.js

      /Buttons
         Button.js
         CircleButton.js

   /screens
      ...

   /utils
      ...

   /services
      ...

   /theme 
      theme.js
     

I have seen people using index.js files for importing/exporting stuff, in order to clean all imports of the app.

Is this the main purpose of index.js? Is it a good practice to have a index.js per directory?

2 Answers

If you need to import multiple files from a folder like:

import {SearchInput} from './components/TextInputs/SearchInput'
import {TextInput} from './components/TextInputs/TextInput'

I would recommend creating an index file. This reduces the amount of import statements you are going to use in other components:

/app
   /components
      /TextInputs
         SearchInput.js
         TextInput.js
         index.js

with the content: (/TextInputs/index.js)

import {SearchInput} from './SearchInput'
import {TextInput} from './TextInput'

export {SearchInput, TextInput}

and use it on the other components like:

import {TextInput, SearchInput} from './components/TextInputs'

This is why the index.js is used mostly, and makes the imports more managable and readable for some cases. Entirely up to developer!

It's likely more personal preference than not, but I think indexes has 2 main benefits.

  • It lets your user know that this file is the key and main file for that directory, like if I see an index.scss in /style I immediately assume that index will @import other partials. If I see an index.js in a root dir I immediately assume it's probably what package.json is referring to. So in a sense it's communicating things to you.
  • Most typescript/react project will allow importing with index without having to specify the index file and it will automatically load it for you.
// ./src/example/index.js

import Example from './src/example'

...

// ./theme/index.scss

import './theme'

Which will automatically import the index.

This also helps a lot when you're using something like css modules or styles per component where it's stored in the same directory, so that you can still import the normal component without having to do something like import Header from './Header/header.js'.

There is a caveat though, while it serves some benefits it can also be difficult to debug sometimes when you have 20 files called index, when one of them breaks and the debugger is only telling you it's in a file called "index.js" without being more specific about which file or what directory.

Related