I am using Gatsby (React) for my project. I am using Atomic design folder structure e.g:

src/components/Organisms/Header

In this folder I like to have:

src/components/Organisms/Header/header.js
src/components/Organisms/Header/header.module.scss

How can I import header.js from within src/components/layout.js like:

import Header from '@components/Organisms/Header'

instead of:

import Header from '@components/Organisms/Header/header'

Update:

I managed to do it by:

  • adding an index.js file to src/components/Organisms/Header/
  • and export { default } from './header'; in index.js

But are this best practices?

1

There are 1 best solutions below

1
coreyward On

You have a few options here. With all of these you would import src/components/Header.

1. Flat with no component directory (my preference):

src
└── components
    ├── Header.js
    └── header.module.css

Benefits

  • Less meaningless nesting
  • No conflicting/confusing filenames open in your editor (e.g. index)
  • Easy to follow the imports and exports

Drawbacks

  • Nowhere for one-off resources and sub-components to go

2. Adjacent component and resources-directory (Ruby-style):

src
└── components
    ├── Header
    │   ├── header.module.css
    │   └── logo.png
    └── Header.js

Benefits

  • Resources and sub-components are kept together
  • No conflicting/confusing filenames open in your editor (e.g. index)
  • Easy to follow the imports and exports

Drawbacks

  • The component isn't adjacent to resources, so imports require a ./Header/ prefix
  • Depending on the sorting, the resources directory may not be listed immediately adjacent to the component

3. With a directory index that exports Header:

src
└── components
    └── Header
        ├── Header.js
        ├── header.module.css
        ├── index.js
        └── logo.png

Benefits

  • Component and resources are kept together
  • Sorting doesn't matter

Drawbacks

  • Conflicting/confusing filenames open in your editor (e.g. index)
  • Confusing imports and exports, may cause hard-to-diagnose errors
  • Extra work for every component