Export class as a module in webpack

I’m using Webpack to import a javascript file that has a single class.

my_class.js

console.log('hello from my_class');

class myClass {
    // ...
}

index.js

import './my_class.js';

webpack.config.js

const path = require('path')

module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
}

I’m trying to use this class on a page.

index.html

<script src="./dist/bundle.js"></script>
<script>
    
    const myClass = new myClass();

</script>

I am able to seem my console log ("hello from my_class") but myClass is showing up as undefined.

Uncaught ReferenceError: myClass is not defined

What do I need to do such that myClass is exported and available in the markup?

1 thought on “Export class as a module in webpack”

  1. Firstly you should export the class.

    export class myClass {
        // ...
    }
    

    And for browsers you should use IIFE or UMD format:

    output: {
      library: 'someLibName',
      libraryTarget: 'umd',
      filename: 'bundle.js'
    }
    

    2021 and webpack thinks federated apps are higher priority than adding ES module support 🤷‍♂️ Use rollup if you don’t want to use UMD.

    And reference: someLibName.myClass

    Reply

Leave a Comment