0

I am refactoring my javascript code to make it more object-oriented, but I cannot get the newest features applying classes to work!

First, I declare the class in a separate file as follows:

// models/player.js 
export default class Player {

   constructor() {
      //loads of code
   }
}

Then, I refer to the file in my html as follows:

<script src="js/models/player.js" type="module"></script>
<script src="js/game.js" type="text/javascript"></script>

Finally, I try to import the class into my main js file as such:

// game.js
import Player from './models/player';

But for some reason, Chrome (even Canary) throws me the "Uncaught SyntaxError: Unexpected Identifier" in that very first import line!

I'm trying to follow all the specifications and examples I can find online. What am I missing?

2
  • You can only use import in a script with type=module. Commented Nov 8, 2018 at 15:42
  • Ahhhh.... I thought it was the other way around! Commented Nov 8, 2018 at 16:44

1 Answer 1

2

import and exports are only good to use in module system like using webpack, etc. But when you directly insert the script file you don't need it:

// models/player.js 
class Player {

   constructor() {
      //loads of code
   }
}

<script src="js/models/player.js" type="text/javascript"></script>
<script src="js/game.js" type="text/javascript"></script>

Now, you can directly use that class: (in game.js)

new Player

If you prefer using import export even while inserting script then you must specify its type to be module:

<script src="js/models/player.js" type="module"></script>
<script src="js/game.js" type="module"></script>
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh...! I thought I needed to use "import" with classes, but if you put it like that, I'd rather be without! Thanks! This looks like the answer I'm looking for!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.