Javascript import class from file yields “Uncaught

2020-05-05 05:37发布

问题:

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?

回答1:

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>