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

I am using babel / ES6 with webpack. I am importing the same โ€œactionโ€ file, which exports the bundle functions, in two different places. In one place, it returns a module, another 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); 

change the reason why App.js worked was that it actually used import * as actions , as I said below, I just incorrectly indicated 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 modules / files?

+5
source share
3 answers

This should not work in any case, because you are importing the wrong values. import foo from '...' imports the default export, but you do not have a default export, you only have a default export.

What you should use is

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

I ran into a similar problem caused by circular dependencies. I tried to import the constant into file "A" from file "B", which, in turn, tried to import from file "A".

+10
source

Another common case when this happens is that you test with Jest and auto bullying is activated. Very sad, so good.

0
source

Source: https://habr.com/ru/post/1237179/


All Articles