Flion Flion - 1 month ago 6
React JSX Question

imported function is undefined in one file, not in another - ES6

I'm using babel / ES6 with webpack for a React + Redux project.
I'm importing the same 'actions' file - which exports a bunch functions - in two different places. At one place it returns a module, the other undefined:

actions.js

export function test() { ... }
export function test2() { ... }


App.js

import actions from './actions'
class App extends React.Component { ... }
console.log(actions); //<-------- Object{test:function,test2:function)
export default connect((state) => { ... },actions)(App);


edit
the reason App.js worked was because it was actually using
import * as actions
as sugested below, I just retyped it wrong in the example

NestedComponent.js

import actions from './actions'
class NestedComponent extends OtherComponent { ... }
console.log(actions); //<-------- logs undefined
export default connect((state) => { ... },actions)(NestedComponent);


How can it be undefined? Can it have something to do with the order in which webpack defines the modules/files or something?

Answer

This shouldn't work in either case because you are importing the wrong values. import foo from '...' imports the default export of the module, but you don't have a default export, you only have named exports.

What you should use is

import {test, test2} from './actions';
// or
import * as actions from './actions';