Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda