Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 797
PopKernel Avatar asked Jan 07 '18 18:01

PopKernel


3 Answers

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>
like image 81
T.J. Crowder Avatar answered Nov 19 '22 08:11

T.J. Crowder


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.

like image 39
The Reason Avatar answered Nov 19 '22 10:11

The Reason


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.

like image 2
Himanshu Soni Avatar answered Nov 19 '22 09:11

Himanshu Soni