简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM