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?

ultraGentle
  • 5,084
  • 1
  • 19
  • 45
  • 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](https://stackoverflow.com/questions/53023279/javascript-how-to-make-es6-imports-work-in-browser) and in Node? – VLAZ Jan 14 '20 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? – ultraGentle Jan 14 '20 at 16:08
  • [You should be able to use `import` in the browser](https://www.sitepoint.com/using-es-modules/) – VLAZ Jan 14 '20 at 16:10
  • Thanks, I wasn't aware of that. – ultraGentle Jan 14 '20 at 16:13
  • There are many many different ways to accomplish this. It depends on your toolchain and the browsers you support – Aluan Haddad Jan 14 '20 at 20:50
  • Does this answer your question? [How can I share code between Node.js and the browser?](https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser) – JΛYDΞV Jun 18 '22 at 04:31

0 Answers0