ahsan's avatar
Level 46

ES6 Class does not work in compiled js

Hi,

i have this class in my /src/js/main.js

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return `(${this.x}, ${this.y})`;
    }
}

export default Point;

here is the webpack.mix.js file

let mix = require('laravel-mix')

mix.js('src/js/main.js', 'dist/')
   .setPublicPath('dist')

so when i include in my index.html file like this:

<!DOCTYPE html>
<html>
<head>
    <title>es6 test</title>
</head>
<body>

    <!-- Scripts -->
    <script src="dist/main.js"></script>

    <script type="text/javascript">
        new Point(1, 3)
    </script>
</body>
</html>

so i have this error in console

"Uncaught ReferenceError: Point is not defined"

Actually, i want to create npm package for users to just include my script and instantiate the script

like this

new Point(1, 3)

is there any solution?

Thanks

0 likes
1 reply
sustained's avatar

Perhaps this...

if (typeof window === 'undefined')
    export default Point;
else
    window.Point = Point;

No idea what best practice is though regarding this.

Since the stuff I import/require in my app/main JS file are only being used in the browser personally I just do stuff like window.Blah = require('blah'); or import Blah from 'blah'; window.blah = Blah;.

Please or to participate in this conversation.