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

222
Vistas
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 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