react exporting and importing components

时间:2018-02-03 07:41:36

标签: reactjs

I was going through a codebase and this is what I see there.

Basically they have created a component in another file, say CheckIn and they create a CheckIn component in that file and export it like this

module.exports = CheckIn

and after that in the index file they are again importing it and exporting it.

import CheckIn from './components/CheckIn';

export default CheckIn;

what kind of exporting is this? and why is this needed/used?

EDITED to add one more thing which is quite similar , would appreciate an explanation for the below code too. is the View being exported below also have the scss styles exported with it?? I have also seen something like this:-

import PageView from './components/View';
import './view.scss';

export default View;

so, how does that work?

1 个答案:

答案 0 :(得分:0)

This is a common practice to re export all the files in folder using index.js. When you import without specifying file name but only specify folder name then import will try to find index.js file in that directory and will import index.js.Suppose you have following directory structure

\-- component
    \-- checkin.js
    \-- index.js
\-- someFile.js

If you want to import checkin.js file in someFile.js then you would write

import Checkin from "./component/checkin"

But if you are re-exporting the checkin in index.js file as you mentioned in the question, then you won't have to specify the file name and you can directly import the file in someFile.js like this

import Checkin from "./component"

This will look for index.js file in component folder and will import that.

Also if there are multiple files in a directory

\-- component
    \-- A.js
    \-- B.js
    \-- C.js
    \-- index.js
\-- someFile.js

Then you can export all of them in index.js file

// index.js
export A from './A';
export B from './B';
export C from './C';

And then in someFile.js you can import them like this

import {A, B, C} from "./component"