jvv8's avatar
Level 2

How to load Javascript ES6 Class in view?

Is there a requirement that I'm missing to have ES6 classes available for use in the view? If I declare the following in public/js/person.js:

Class Person {
    constructor(data){
        name = data.name;
    }
}
export default Person;

Then somewhere in my mix file I have: mix.babel(['public/js/person.js'],'public/js/person.min.js'); Then in the view:

<script src="{{ mix('js/person.min.js') }}"></script>
<script>var bob = new Person({name: "Bob"});</script>

I get the error: Uncaught ReferenceError: Person is not defined

Am I missing something? L5.4 [email protected]

0 likes
3 replies
rawilk's avatar

you have to use import. Also, I'm not sure if you can import in a blade as I've never tried it; I always am using external scripts for everything, that way everything can be in laravel mix.

import Person from './path/to/person.js;
1 like
spekkionu's avatar

You will also need to run the script that uses the class through babel to be able to use the class as browsers do not understand module loading.

Alternatively you can remove the export default Person; line from your class file and include it with a script tag without running it through babel and it will work in browsers that understand classes (all but IE, https://caniuse.com/#feat=es6-class)

If you use module loading you have to use it everywhere and cannot use inline code in script tags unless inside one of your trans-piled scripts you set the module to the window object which basically sets it as global.

jvv8's avatar
jvv8
OP
Best Answer
Level 2

I did get it to work by:

  • Removing 'export default Person;' For some reason I kept getting "exports is not defined" error near:
Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function t(t,i)....
  • Changing the instantiation to:
window.bob = new Person({name: "Bob"});

Not sure why as this is my first use of ES6 classes.

Please or to participate in this conversation.