Escher Escher - 1 year ago 64
Javascript Question

how to instantiate an es6 class after it's been bundled into a function by webpack

I was following an es6 classes tutorial and made a nice little d3 visualization. Then I made a second, and thought I should do something about bundling them into a library, so initially tried modules (then discovered browsers don't support them yet), and then I installed webpack 1.13 and used

(because although it seemed like
should work, it didn't; not supported until 2.0).

Only, now instead of
export default class Foo(data, args)
in my bundle.js I've got
var Foo = function () { function Foo(data, args) ...

The interpreter just complains when I try to
Foo.Foo(data, args)
, but my intuition here is that pretend-instanting a frankenclass this way probably isn't what webpack intends? And yes, I could just concatenate all my module files into my own bundle.js and then go
new Foo()
, but I'm trying to use a proper bundling tool.

I feel like there's quite a gap in the online documentation between what's "possible" in ES6, and how you actually make it happen in webpack.

What's the step-by-step way of bundling modules with webpack such that you can instatiate your classes from the bundle in your index.js script?

Appendix: (What I've done so far)

├── bundle.js #supposed to bundle Foo and Bar
├── index.html #include bundle.js and index.js before </body>
├── index.js #want to be able to new Foo() and Bar()
├── js
| ├── foo.js Foo() lives here
| └── bar.js Bar() lives here
├── node_modules
| └── (stuff)
├── package.json
├── test
| └── (stuff)
└── webpack.config.js # builds without errors

Answer Source

Webpack is a bundler. That means after you run webpack, it parses all your files and puts them into one, (or more if using something like CommonsChunkPlugin).

Everything inside the bundle is then private, so if you want to share your classes, code etc. you will then to need to expose them, can do this, but in essence all it's doing is placing stuff on the global namespace, in browsers the global namespace is usually the window object.

A better approach though to sharing code with other webpack uses, is for you to just show him were your code is, and then he can compile into his webpack bundle,. He can even do automatic bundle splitting with require.ensure, this would be handy if say your Class is not used very often, so it would load on-demand.

Hope the above makes sense, as I remember when I first started using webpack, it did seem overwhelming at times, and the documenation isn't the greatest for beginners.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download