Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using ES6, how can an imported function be undefined in one file, and not in another?

I'm using babel / ES6 with webpack. 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);

Is this related to the order in which webpack defines the modules/files?

like image 496
Flion Avatar asked Dec 01 '15 16:12

Flion


2 Answers

I ran into a similar issue, caused by circular dependencies. Tried to import a constant in file 'A' from file 'B' which in turn tried to import from file 'A'.

like image 181
user1583875 Avatar answered Sep 20 '22 13:09

user1583875


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';
like image 45
Felix Kling Avatar answered Sep 22 '22 13:09

Felix Kling