Saturday, March 11, 2017

quick note on webpack imports and es6 class inheritance

I know it's crazy that I'm only now using modern javascript class inheritance for the first time, but I've been more of a backend programmer most of my career.

I've got a new hobby project that I'm doing with modern webpack / es6 / vue.js, and I just learned something that I didn't find an obvious answer to in the googs.

Basically, I'd been creating utility files with instantiated objects saved as var whatever or let whatever and then exported at the bottom:

export default {
  obj: obj
}

And this was all well and good. But then when I wanted to define a class in the same file, the export default was overriding keyword "this". So the functions defined on the class referencing this were actually referencing my export default. I could use a fairly circular reference to get back to the instantiated class object, but really that whole route is silly.

The way to make this work is to define (but not instantiate) each class in its own file. The class itself is your export default in that file:

export default YourClass extends Whatever {
  constructor () {
    this.stuff
  }
  yourFunction () {
    this.stuff + 1
  }
}

Then instantiate the class and use it in another file. Should have been obvious but well es6 takes some getting used to.