Search code examples
javascriptecmascript-6

javascript es6 import "expects exactly one argument"


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. 😊


Solution

  • 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, and module specifiers must be relative paths (unless you're using a bundler or an import map), so you need to change:

    <script src="gameTest.js"></script>
    

    to

    <script type="module" src="./gameTest.js"></script>
    

    More in MDN's documentation or Chapter 13 of my book.