Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: How to expose a class constructor to browser’s global namespace

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>
like image 981
IdoTuchman Avatar asked Oct 14 '25 07:10

IdoTuchman


1 Answers

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.

like image 58
Anastazy Avatar answered Oct 17 '25 15:10

Anastazy