require working but import not working

xtabbas picture xtabbas · Nov 23, 2016 · Viewed 8.1k times · Source

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));

Answer

artem picture artem · Nov 23, 2016

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));