I'm trying to use es6 modules but I'm hitting an error:
SyntaxError: Unexpected identifier 'GameObject'. import call expects exactly one argument.
This is in Safari 11 on macOS 10.13, by the way.
Here's my module:
export class GameObject {
//code
}
export class GameLoop {
//code
}
relevant html:
<body>
<script type="module" src="gameFoundation.js"></script>
<script src="gameTest.js"></script>
</body>
and the script that tries to use the module, which gives the aforementioned error on line 1:
import GameObject from "./gameFoundation.js"
import GameLoop from "./gameFoundation.js"
class Rect extends GameObject {
//code
}
I'm new to JavaScript, so I imagine I'm getting something basic wildly wrong. Any help would be much appreciated. 😊
Your exports are named, but you're using default import syntax. You need to wrap the names of what you're importing in {...}
:
import { GameObject } from "./gameFoundation.js";
import { GameLoop } from "./gameFoundation.js";
You can also do both with one import declaration if you like:
import { GameObject, GameLoop } from "./gameFoundation.js";
Also note that import
is only valid in a module, so you need to change:
<script src="gameTest.js"></script>
to
<script type="module" src="gameTest.js"></script>
Named exports will work for you.
Replace
import GameObject from "./gameFoundation.js"
import GameLoop from "./gameFoundation.js"
to
import { GameObject, GameLoop } from "./gameFoundation.js"
Here is a good article about all ES6 import/exports. Will be useful to read for you.
You are using ES6 syntax which needs to be transpiled into native plain old javascript syntax to get loaded into the browser.
Please, refer to the following link: https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them
It will guide you about transpiler that may solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With