I have file to export 'item-state-manager.js':
module.exports.aggregate_states = function (member_states) {
console.log(member_states);
}
other file should import this module and use function 'aggregate_states':
var aggregate_states = require("./item-state-manager.js")
module.exports.saveItem = function () {
var aggregate = aggregate_states("state");
}
But i receiving error:
TypeError: aggregate_states is not a function
Do I import 'item-state-manager.js' wrong?
5 Answers 5
As I know require returns the module.exports object.
If aggregate_states is your only function you want to export use this.
module.exports = function (member_states) {
console.log(member_states);
}
Otherwise import it like this.
var aggregate_states = require("./item-state-manager.js").aggregate_states;
Comments
Recently I hit into the same sort of error, TypeError: (0 , _store.withToken) is not a function when running my (minimal) test suite on a project. Confusingly, the function withToken was fine in many of the tests, but not in others.
After a lot of digging in, I finally narrowed it down to being an issue with a cyclical dependency.
Refactoring my code so that the cyclical dependency was removed fixed the issue and the error disappeared. Specifically, I had to bring some of the files that referenced each other into one larger file, which is a little less tidy but removes this issue.
In my instance, because my withToken function referenced the store, and the store referenced withToken, both functions cannot have been setup at the same time, so to setup store, withToken needs importing, and to use withToken it needed the imported store.
2 Comments
You are not importing the module correctly. Either import directly the funcion using
var aggregate_states = require("./item-state-manager.js").aggregate_states;
or import the module and call the function
var stateManager = require("./item-state-manager.js");
// And use it like this
stateManager.aggregate_states(/*...*/)
If you are using an up to date version of node, you can also do
const { aggregate_states } = require("./item-state-manager.js");
Comments
Try this:
var aggregate_states = require("./item-state-manager.js").aggregate_states;
module.exports.saveItem = function () {
var aggregate = aggregate_states("state");
}
aggregate_states is just a property of the entire returned module, when you require you get the entire module which is an Object that looks like this:
{
aggregate_states: function() {...}
}
Comments
------ AT THE EXPORTING FILE
declare the function you want to export normally... function aggregate_state(member_states)
at the end of that .js file add... module.exports = { aggregate_state : aggregate_state, }
------ AT THE IMPORTING FILE
import the file you want... const aggregate_states = require("./item-state-manager.js");
call it... item-state-manager.aggregate_state(member_states);