4

This is an ES6-specific duplicate of this SO thread, which details how to create a javascript module that can be exported for use in both a browser and node context.

I would be just as glad for an answer to appear there, if that's more appropriate.

For background, here's a quote of the ES5 solution, as well as the problems that arise in trying to translate it to ES6. (Credit to users @caolan and @broesch.)

(function(exports){

    // Your code goes here. For example: 
   exports.test = function(){
        return 'hello world'
    };

})(typeof exports === 'undefined'? this.mymodule = {} : exports);

Thus, if exports is undefined, you must be in the browser, in which case mymodule is declared on the window (i.e., this). Or, if exports is defined, it's in a node context, in which case you can just var mymodule = require('mymodule'). And in either environment, you can then use it as mymodule.test(). Great.

One problem with this is that exports.whatever doesn't expose whatever in the current scope, so if you want to use whatever within the module, you end up needing to do

var whatever = 3;
exports.whatever = whatever;

which can get cumbersome, and is easy to forget.

In ES6, on the other hand, you can do export const whatever = 3, which would both export and expose whatever, which is DRYer and thus easier to maintain.

The new problems are that

  1. export must be at the top level of the file, which means you can't use the syntax from the ES5 answer
  2. export isn't a function (is it?), so you can't use type of to achieve the conditional browser/node context.

So, my question is: what is the ES6 version of creating a .js file that can exported to both the browser and node?

6
  • 1
    "what is the ES6 version of creating a .js file that can exported to both the browser and node?" it's just a module that you can use in the browser and in Node? Commented Jan 14, 2020 at 15:28
  • 1
    @VLAZ Thanks for the reference. But you can't write import * from myFrontBackSharedFile as mymodule in the browser context, so can you clarify the syntax to reference/namespace the module in the browser code? Commented Jan 14, 2020 at 16:08
  • You should be able to use import in the browser Commented Jan 14, 2020 at 16:10
  • Thanks, I wasn't aware of that. Commented Jan 14, 2020 at 16:13
  • There are many many different ways to accomplish this. It depends on your toolchain and the browsers you support Commented Jan 14, 2020 at 20:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.