Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require working but import not working

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));
like image 327
xtabbas Avatar asked Nov 23 '16 10:11

xtabbas


People also ask

How do you use require and import at the same time?

Just two lines of code: // These lines make "require" available import { createRequire } from "module"; const require = createRequire(import. meta. url);

How do I convert require to import?

Convert your require() 's into ES Module imports by clicking the 💡️ lightbulb icon and selecting 'Convert to ES6 module'. Using this feature can convert your code from this: const path = require('path'); const crypto = require('crypto'); const fetch = require('node-fetch'); const {name} = require('./animal. js');

Are require and import interchangeable?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .

Can I use import in node instead of require?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.


1 Answers

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));
like image 140
artem Avatar answered Oct 12 '22 11:10

artem