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));
Just two lines of code: // These lines make "require" available import { createRequire } from "module"; const require = createRequire(import. meta. url);
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');
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 .
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With