Reputation: 40
I'm really suffering here due to some awful inconsistencies in importing/exporting modules in Node.js.
It's easier to see:
//game.js
const {Player} = require("./player");
{...}
console.log(Player); //outputs undefined
//player.js
class Player {
constructor(client, host = false) {
this.properties = {...client};
this.host = host;
this.hand = [];
}
{...}
}
module.exports = {Player};
This may seem fine but here's the strangest part. Inside another file, deck.js
, I export in the exact same way. And it gets correctly recognized in game.js
.
//game.js
const {Deck} = require("./deck");
console.log(Deck); //outputs "[Function: Deck]"
//deck.js
class Deck {
constructor() {
this.deck = [...compressed_cards];
this.shuffle();
}
{...}
}
module.exports = {Deck};
These are both local files, as you can see. I can import deck.js just fine but not player.js, despite the exact same methodologies. I've tried module.exports.Player = Player
, I've directly set module.exports.Player = class Player {...}
, it just won't seem to work. To whoever figures this out and makes me look like an idiot, thanks.
Oh, and to add to my confusion, I can import player.js
in other files outside of the folder just fine. But not inside. Why. And of course, all of my other files can access each other in the exact same way without any issues.
File structure looks like this:
Upvotes: 1
Views: 63
Reputation: 5245
The reason could be that you have circular dependencies. That means player.js
might require game.js
or deck.js
, such that when you draw lines between files that require each other, you will see a full circle. The suggestion is to restructure your dependencies to avoid such dependency structure.
More about circular/cyclic dependencies is discussed here: How to deal with cyclic dependencies in Node.js
Upvotes: 1
Reputation: 123
According to this article you should be able to import / export a class like this:
//game.js
const Player = require("./player");
//player.js
class Player {...}
module.exports = Player;
Upvotes: 0