Reputation: 75
So I am preparing to make a sandbox game with pure coding, and I want to make a separate file for a class called Block
in my testing code. Here's the code:
package.json
{
"name": "speedbox",
"description": "SpeedBox is a simple SandBox game owned by Dean Summer (SpeedoThreeSixty).",
"version": "1.0.0",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/JavascriptLearner815/SpeedBox.git"
},
"keywords": ["speedo", "speedothreesixty", "sandbox", "box", "speed", "speedbox"],
"author": "Dean Summer <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/JavascriptLearner815/SpeedBox/issues"
},
"homepage": "https://github.com/JavascriptLearner815/SpeedBox"
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="SpeedBox is a simple SandBox game owned by Dean Summer (SpeedoThreeSixty).">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>SpeedBox - Home</title>
<link rel="stylesheet" href="./main.css">
<script defer src="block.js" type="module"></script>
<script defer src="index.js" type="module"></script>
</head>
<body>
<button id="createBlock">Create a block!</button>
</body>
</html>
main.css is empty
index.js
try {
import { Block } from "./block";
globalThis.blocks = [];
var createBlockButton = document.getElementById("createBlock");
createBlockButton.addEventListener("click", () => {
const newBlock = new Block(1);
blocks.push(newBlock);
});
} catch (error) {
console.error(error);
}
block.js
export default class Block {
constructor(id) {
try {
if (globalThis.blocks.length === 5) throw "Cannot exceed block limit";
this.id = id;
if (this.id === 1) this.type = "grass";
console.log(`Created block of type ${this.type}`);
} catch (error) {
console.error(error);
}
}
}
No matter what I try, I always get one of these error messages:
Uncaught SyntaxError: Cannot use import statement outside a module index.js:2
Uncaught SyntaxError: Unexpected token '{' index.js:2
Uncaught SyntaxError: Unexpected identifier index.js:2
How can I import this module?
Upvotes: 0
Views: 1653
Reputation: 664528
The error message is a bit confusing, but you cannot use an import
declaration inside a try
block. It needs to be at the top level of the module code:
import { Block } from "./block"; /*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
try {
globalThis.blocks = [];
var createBlockButton = document.getElementById("createBlock");
createBlockButton.addEventListener("click", () => {
const newBlock = new Block(1);
blocks.push(newBlock);
});
} catch (error) {
console.error(error);
}
Upvotes: 1