Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!