I'm new to webpack and can't figure out how to expose a class constructor to the browser’s global namespace. For example, how do I configure webpack so that the code below prints “hello world” in the console? I've tried using exports-loader, expose-loader, and script-loader without success.
main.js
class MyClass {
print() {
console.log('hello world');
}
}
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="./dist/bundle.js"></script>
<script>
myClass = new MyClass;
myClass.print();
</script>
</body>
</html>
You can either:
a) Expose your function (class) explicitly:
main.js
class MyClass {
print() {
console.log('hello world');
}
}
window.MyClass = MyClass;
Then you can call your constructor from global object by referencing MyClass directly.
b) Configure webpack to expose your exports in a global object as follows:
webpack.config.js
module.exports = {
output: {
library: 'someName',
libraryTarget: 'umd',
globalObject: 'this'
}
}
Then you can call your constructor by referencing exported function (class) in a global variable configured as library option in above config file. In this example someName.MyClass. For this to work you must export the function in main.js file, as shown below.
main.js
export class MyClass {
print() {
console.log('hello world');
}
}
Refer to webpack output configuration for more specifics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With