Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
Melissa Diaz Avatar asked May 27 '26 01:05

Melissa Diaz


2 Answers

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

like image 178
Dominic Avatar answered May 28 '26 14:05

Dominic


As you have not exported class from my_class.js file, you will not be able to import it.

console.log('hello from my_class');

class myClass {
    // ...
}

export default myClass;

And your import should be like

import myClass from './my_class.js';
like image 42
Garud Pragati Avatar answered May 28 '26 14:05

Garud Pragati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!