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

221
Visualizações
Cannot use conditionally use export keyword on Node.JS server when trying to use code shared between server and client?

I have a JS file that contains a bunch of constants and a few primitive functions in a module named global-namespaces.js. I am now trying to upgrade my code on the client side to use modules and the import statement. By the way, I know the code below looks awkward but that's because I'm struggling to find a solution still.

On the server side I just use require(). However, I can't seem to find a way to export the needed symbols from global-namespaces.js when used in the client side context that doesn't generate a syntax error on the server side. I can't put the export block/keyword in an IF statement because that generates a syntax error. Here is my current code:

    try {
        g_GlobalNamespaces = new GlobalNamespaces();
    } catch(err) {
        console.error(`${errPrefix}Error occurred during the creation of the global GlobalNamespaces object.`);
        console.info(errPrefix + `err object:`);
        console.dir(err, {depth: null, colors: true});
    }

    // Use this code on both client and server side.  Are we on the server side?
    if (typeof module == 'undefined' || typeof module.exports == 'undefined')
    {
        // No. g_GlobalNamespaces is already in the client side global namespace.
    } else {
        // Yes.  Export the code so it works with require().
        module.exports =
            {
                g_GlobalNamespaces: g_GlobalNamespaces
            }
    }

    //  We export it so it can be used via "import" statements.
    export // THIS STATEMENT GENERATES THE SYNTAX ERROR ON THE SERVER SIDE.
    {
        g_GlobalNamespaces
    }

This SO post has no answers:

How to share code between client and server when using Node.js

And this SO post only handles the client-side only case and doesn't help me with the client and server side sharing issue:

Conditional export in ES2015

How can I structure global-namespaces.js so I can use the code both on the server and the client side?

about 4 years ago · Juan Pablo Isaza
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