Bundling ES6 classes with Webpack. Is there a way to hoist extended classes?

后端 未结 1 514
悲哀的现实
悲哀的现实 2021-01-24 13:19

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

相关标签:
1条回答
  • 2021-01-24 13:33

    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.

    0 讨论(0)
提交回复
热议问题