Can Webpack hoist extended classes?
I am using Webpack and Babel to bundle and transpile a bunch of classes, each from a separate file.
My Webpack entry file is an index.js file containing import statements of every class ordered by name,
index.js:
import classA from './a';
import classB from './b';
import classC from './c';
import classD from './d';
...
a.js:
export class classA extends classD {
constructor(...) {
super(...);
}
}
My problem is that the classes gets imported ordered by name, so classD
will be declared after classA
and will break the program because of javascript hoisting/initialization rules.
So my question is if there is a way for Webpack to sort the classes and put them in the necessary order? Or is my only choice to sort them manually?
Webpack does not simply put all the imports together into one file, but it keeps them as modules. Every module/file needs to import everything it depends on, so it would work if you just run that module in Node (after transpiling if necessary). Your a.js
does not work by itself because classD
is not defined. The correct way is to import it in a.js
:
import ClassD from './d';
export default class ClassA extends ClassD {
constructor(...) {
super(...);
}
}
import x from './file'
imports the default export as x
, so you want to use export default
for your classes.
You might be worried that importing a file from multiple places will include it multiple times, but that is not the case, it's included once and every import of that module will refer to the same one in the bundle.
Note: The convention in JavaScript is to use PascalCase for classes.