1

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:

this

lanye74
  • 40
  • 10
  • player.js and game.js are in the same folder? – crogers Apr 19 '20 at 05:51
  • They definitely are – lanye74 Apr 19 '20 at 15:24
  • 1
    I suspect 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. More about circular/cyclic dependencies: https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js – thammada.ts Apr 29 '20 at 19:12
  • Yeah, I have player.js requiring an object from game.js; I didn't know it was an issue but I'll see how to fix that if it is my problem – lanye74 Apr 29 '20 at 19:19

2 Answers2

1

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

thammada.ts
  • 5,065
  • 2
  • 22
  • 33
  • That was my issue, I moved the object I was requiring into my player file and it worked like a charm, thanks – lanye74 Apr 29 '20 at 19:24
0

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;

JorgeZapatero
  • 123
  • 11