Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda