因此,我准备使用纯编码制作沙盒游戏,并且我想为Block
测试代码中调用的类制作一个单独的文件。这是代码:
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为空
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);
}
}
}
无论我如何尝试,我总是收到以下错误消息之一:Uncaught SyntaxError:无法在模块index.js之外使用import语句:2 Uncaught SyntaxError:意外的令牌'{'index.js:2 Uncaught SyntaxError:意外的标识符索引。 js:2
我确实有Node,但是在此示例中我不想使用它。另外,该问题在过去已经发生。
错误消息有点令人困惑,但是您不能import
在try
块内使用声明。它必须在模块代码的顶层:
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句