Package an ES6 class from node to browser

Viewed 361

I have been trying to package a super simple ES6 style class object to the browser. Example

class Foo {
   constructor(){
        this.name = "Foo";
   }
}
module.exports = Foo;

Sure I can use this in my node projects just fine, but it's also a useful object for the browser. So far I have tried webpack and browserify, but they do not expose the object globally. I was hoping to basically include the generated script file and be able to call let foo = new Foo() from the browser. How can I do this?

*note that literally the only thing stopping me from just including the file in the browser directly is the module.exports

2 Answers

Without hacking a huge library, or building another node module to somehow automate this, I thought of that famous razor today and just did this.

if(typeof module !== "undefined"){
    module.exports = Foo;
}

For Javascript 6 you wanna do something like:

class Foo {
   constructor(){
        this.name = "Foo";
   }
}
export default Foo;

(use export instead of module.exports)

Then from another js file do:

import Foo from '<path_to_foo>';

For example, if Foo.js is in the same dir as the "other" module, then you can do: import Foo from './Foo';

Then you can do let f = new Foo()

Modern browsers tend to support js modules, however it is not guaranteed.

Hope this helps

Related