2

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?

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227

0 Answers0