Khorkhe
Khorkhe

Reputation: 1126

import and export of modules in ES6

I am in the process of refactoring my structure of import and export of modules. The goal here is to import UserActions through index.js, in multiple files (namely, in UserReducer.js and Home.js).

the project's tree structure looks like:

js
|_ modules
|  |_ user
|  |  |_index.js
|  |  |_UserActions.js
|  |  |_UserReducer.js
|  |  |_UserSagas.js
|_ containers
|  |_ Home.js

This is the content of modules/user/index.js:

import * as UserActions from './UserActions'
import * as UserSagas from './UserSagas'
import UserReducer from './UserReducer'

export { UserActions, UserReducer, UserSagas }

Initially the actions were being imported directly from the UserActions file, in both UserReducer.js and Home.js as follows:

And everything was working correctly. Now I want these two imports to use the index.js file above.

step 1)

inside UserReducer, i change the import line from:

import * as UserActions from './UserActions'

to:

import { UserActions } from '.'  // fetches the named export from index.js

This is working.

step 2)

inside Home.js, i change the import line from:

import * as UserActions from 'modules/user/UserActions'

to:

import { UserAction } from 'modules/user'

Now webpack doesn't complain but the browser throws error in UserReducer, that UserActions is undefined.

Finally:

using the import { UserActions } from 'path_to_index.js' notation works, as long as I use it in one place only (could be in either file).

As soon as I use it in both places, all hell breaks loose...

Any ideas? Thanks

Edit: I realize that the errors above occur only if the user/index.js imports and exports UserSagas as well. If I import the UserSagas directly from their file instead of adding it to index.js, the app runs correctly.

Upvotes: 0

Views: 978

Answers (1)

Khorkhe
Khorkhe

Reputation: 1126

Turns out @estus is correct in that even importing another exported part from index.js would cause circular dependency.

I wanted index.js to be the unique interface to users, but it looks like that will only apply to components outside of "users". Internally, the import will be directly from the actions file

Upvotes: 1

Related Questions