'How to properly export/import an object in this nodeJS project?

I have a nodeJS project where I have this file GameState.js with this structure:

const GameState = function(socket){
  this.socket = socket
  //quite a large constructor so I removed most of it
};

//defining all the prototype methods
GameState.prototype.getSocket = function() {
  return this.socket
}

module.exports = GameState;

I'm able use this GameScreen constructor in my gamescreen.js file, by having the two scripts in my gamescreen.html file like this:

<script src = "gamestate.js"></script>
<script src = "gamescreen.js"></script>

So for getting GameState into gamescreen.js I actually don't need the module.exports, it's even giving me a (non-breaking) ReferenceError when I use the app, which is quite annoying.

However with my current structure I can't remove this module.exports as I also have a test file (using jest) where I import GameState with require like this:

const GameState = require("../scripts/gamestate.js");

//the tests here...

So my question is: How do I get GameState in both gamescreen.js and gamestate.test.js, without having the ReferenceError? Right now it's all working, but it's not very optimal to get an error in the console when running the app.

EDIT: A better way to formulate this question might be: I have a module GameState defined with module.exports, now how do I get it in gamescreen.js (the client-side), without losing the ability to import it with require(...) in a test file?



Solution 1:[1]

I got rid of the error by simply wrapping the module.exports in a try catch block like this:

try {
  module.exports = GameState;
} catch(error) {
  console.log("didn't work")
}

When I run it in the browser it functions normally and prints: "didn't work" and when I run my tests with npm test, the tests work too.

It might not be the prettiest fix, so any other suggestions would be appreciated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user16804967