Home>
Overview

I want to create a class with ES6 and use it with the script tag in another HTML file, but I get an error.
As a premise, ES6 is converted to ES5 using babel-loader in webpack.

Learn more

TestClass.js is created and TestClass is defined as follows.

export class TestClass {
    constructor () {
    }
}

The build result of the above class is output to /dist/build.js
At the point of use, build.js is read as follows to generate an instance of TestClass.

<! DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "utf-8">
    <title>test</title>
  </head>
  <body>
    <div></div>
    <script src = "/ dist/build.js"></script>
    <script type = "text/javascript">
        var b = new TestClass ();
    </script>
  </body>
</html>

But when I run it in a browser,

ReferenceError: Can't find variable: TestClass

is displayed.

My assumption is that TestClass converted to ES5 format is output to build.js, so I thought it could be referenced by another script tag. However, an error occurs.

On the other hand, it seemed that TestClass instance could be generated by js code of webpack entry point.
(It seems that you can refer to the class normally in the js file related to webpack build)

I want to know how to fix the error.

  • Answer # 1

      

    My assumption is that TestClass converted to ES5 format is output to build.js, so I thought it could be referenced by another script tag.

    If you do nothing in particular, the variable name used in Webpack will not be global, it will belocal variable in Webpack code.

    If you want to use it outside, assign it to a global variable viawindow, such aswindow.TestClass = TestClass;.