Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - How do index.js files work in React component directories?

I just started a new React project and decided to use this pattern, which basically groups files according to their respective component:

├── actions
│   ├── LaneActions.js
│   └── NoteActions.js
├── components
│   ├── App
│   │   ├── App.jsx
│   │   ├── app.css
│   │   ├── app_test.jsx
│   │   └── index.js
│   ├── Editable
│   │   ├── Editable.jsx
│   │   ├── editable.css
│   │   ├── editable_test.jsx
│   │   └── index.js
...
│   └── index.js
├── constants
│   └── itemTypes.js
├── index.jsx
├── libs
│   ├── alt.js
│   ├── persist.js
│   └── storage.js
├── main.css
└── stores
    ├── LaneStore.js
    └── NoteStore.js

What's confusing me is how index.js works in this case. As quoted:

The index.js files are there to provide easy entry points for components. Even though they add noise, they simplify imports.

What the article doesn't do is go in depth of what's inside these files. In the case of the Editable component, what would Editable.jsx and index.js ideally look like?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This exact structure suggests that, for example, the Editable component would have everything about that component inside Editable.jsx. and I mean that your component code stays inside that file.

Now what's index for ? Inside index you would simply do something like this:

import Editable from './Editable.jsx';

export default Editable;

and that's it. This is helpful because inside other components or containers you can do this:

import Editable from '../Editable';

because it tries to access the index.js file by default thus not requiring any more info from you. It would import automatically the index.js file which imports the actual component itself. If you did not have an index.js file you would have had to do this:

import Editable from '../Editable/Editable';

which is kind of awkward. I don't like to have an index file that all it does is import a component and export it. What I usually do is just have all my component code inside the index.js file without the need of the Editable.jsx at all. That's up to you so feel free to take the approach you like better.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...