'Best practice for importing component from components library in React.js

When I create components in React, they're all in a folder called component and each component has a dedicated folder with the same name as the component itself, e.g. ../components/Input.

But a big concern is about naming files. In order to avoid having to long paths, I name the component inside the folder Index.tsx so that when I import, I'll only have ../components/Input otherwise, it would be a very ugly import path like ../components/Input/Input.

So, by naming Index.tsx, in my IDE, I end up having too much index files open and then I get lost.

So what I did was to rename all those components file with the same name as the folder Input.tsx and exporting them using named export like export const Input:React.FC<InputProps>=(props)=>{...}, then at the root of my component folder, I created one index.tsx file where I export all those components so that while importing them in my pages, I can just write import {Input} from "../components".

I like this approach, but my next concern is about tree shaking. Because I don't want to import every time the entire components library.

So with the above approach, does React handle automatically tree shaking for us?



Solution 1:[1]

There's a tweet about the possible issues related to re-exporting everything with index files.

If your project has a components/index.js file which re-exports all your components (and does nothing else), that’s one example.

This is bad for performance – for two reasons.

  1. It makes code splitting ineffective.

    When you do

    import { Button } from './components'
    

    you’re importing not only Button but the whole ‘./components’ file. Which means you’re bundling the whole file – with all the components it exports.

  2. It makes bundle initialization more expensive.

    Every time a browser downloads the bundle, it has to execute it – and all its modules as well. If there’re a lot of modules, or some of them do something expensive, this can take a while.

Someone else suggests configuring webpack's sideEffects option so that the tree-shaking can still optimize the bundle as much as possible.

What I'm suggesting is to create small component modules inside the components directory.

- components/
  - Input/          # component module
    - index.ts      # exports public API
    - Input.tsx     # actual component implementation
    - Input.test.tsx
    - Input.scss
    - Input.stories.tsx
    - etc.

Where the index.ts only re-export the public API for this component.

// index.ts
export { Input } from './Input';
export type { InputProps } from './Input';
// etc.

So that we have non-repeating paths when importing, but the filename we're actually working with is named according to the component.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1