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

220
Views
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
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!