Using ES6 Classes When Code Splitting and Bundling with Webpack


Javascript

Updated Jul 3rd, 2021

I wish the tutorial in which there was multiple classes in one file. The key word of static was also used to prevent having to instantiate A new object using the class?

It’s brought up the fact that I didn’t have the best understanding of instantiating with the new keyword why it’s necessary where you do it Do you have to do it how code splitting affects this how bundling affects this etc.

Okay so first off you have export default class class name and there’s only one export default per file.

You can have multiple export class className (which is essentially the same thing without the default keyword). You then import {className} from ‘./file/path’

So when bundling your files you typically have to import your split file and instantiate the class within.

To prevent getting an error in the console Your code usually reads something like “if this element exists then instantiate the class” with the “new Classname” syntax

What I did realize here though that you could still have multiple classes in that one split file. I believe they both just need to be exported (just not more than one as a default as explained above).

Essentially had a case where in the main.js file I am importing a split file and instantiating one class in that file. In the split file I instantiate the second class and all code works as expected.

I don’t think the static keyword is really that much of a thing. In the class-based way that I write code I have the constructor and events and methods all in the class that gets instantiated in the main.js file.

When I want to call a method I just use this.methodName with parentheses to call it.

A big aha that I learned is that When you instantiate an object with a glass using the new keyword and you console.log this newly created object you may not see the Class that created the object’s name in the console. In my case I was seeing the letter e and it was driving me mad as to why. I come to find out It’s because the code is minified it strips it down and changes the name automatically.

Note that a good way to see what class created an object is whatEvs object.constructor.name

A good tip I learned in my travels here was just when code needs to be in its own file or not. Pretty much says there’s excessive file switching versus excessive scrolling. If you’re doing a lot of file switching you could probably have code in the same file. If you’re doing a lot of excessive scrolling then you probably need to split code into different files.