Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing JavaScript files with the same name as directory they're inside

In my React and Webpack project, I have the following project structure of React components:

Component/
├── Component.jsx
├── index.jsx
└── styles.css

The index.jsx file simply imports and exports Component.jsx; the reason being that in files that require it, it allows the usage of the following:

import Component from '../Component'

as opposed to

import Component from '../Component/Component'

However this seems like it may be an unnecessary extra step which requires all new components to follow suit.

With this in mind, my question is: Can I have the best of both worlds? I want to be able to only have Component.jsx and styles.css in my directory, but not have to use the name twice in my import declaration.

like image 844
alanbuchanan Avatar asked Feb 28 '17 22:02

alanbuchanan


1 Answers

Let me suggest you the following structure I personally like:

Your component tree structure (As an example every component has a different folder structure. It is up to you to keep it clean and tidy. Index.jsx in components folder just normalizes access to those components whoever needs them):

src/components/
    Butter/
        Butter.jsx
        index.jsx
    Beets/
        Beets.jsx
    Cabbage/
        index.jsx
    Meat.jsx
index.jsx

Content of components/index.jsx

export Butter from './Butter/index.jsx';
export Beets from './Beets/Beets.jsx';
export Cabbage from './Cabbage/index.jsx';
export Meat from './Meat.jsx';

Some container Borscht.jsx somewhere else in your project which uses those components

import {
    Beets,
    Cabbage,
} from 'src/components';
like image 84
anvk Avatar answered Oct 14 '22 22:10

anvk