require working but import not working
Asked Answered
A

1

8

I have a actions.js file that is exporting actions like this

export var toggleTodo = (id) => {
  return {
    type: 'TOGGLE_TODO',
    id
  }
}

but when i import it using es6 import i get error

Uncaught TypeError: Cannot read property 'toggleTodo' of undefined

but when i require it using common js require it works just fine! Can someone explain to me why is this happening, I mean i read these two are same things... Something seem to be different ?

// var actions = require('actions') working 
// dispatch(actions.toggleTodo(id));

import actions from 'actions' //not working
dispatch(actions.toggleTodo(id));
Ahlgren answered 23/11, 2016 at 10:49 Comment(0)
W
11

There are several different forms of import, each doing slightly different thing. The one you are using

import actions from 'actions' //not working

is for importing default export from actions module. You can see complete list in MDN javascript reference.

It's not working because your action.js module probably does not have default export, and actions come as undefined.

The form that roughly corresponds to require call is this one:

import * as actions from 'actions';

it allows you to access all exported values as properties of actions:

dispatch(actions.toggleTodo(id));

or you can use named import like this:

import {toggleTodo} from 'actions';

then you can use toggleTodo directly:

dispatch(toggleTodo(id));
Westfalen answered 23/11, 2016 at 22:9 Comment(1)
This didn't work for me for Typeorm. import * as typeorm from 'typeorm'; still gives the same error.Kokura

© 2022 - 2024 — McMap. All rights reserved.