Javascript 未捕获的SyntaxError:在导出和导入类时,无法在模块外部使用import语句

Javascript 未捕获的SyntaxError:在导出和导入类时,无法在模块外部使用import语句,javascript,syntax-error,es6-modules,Javascript,Syntax Error,Es6 Modules,所以我准备用纯编码制作一个沙盒游戏,我想在测试代码中为名为Block的类制作一个单独的文件。代码如下: package.json { "name": "speedbox", "description": "SpeedBox is a simple SandBox game owned by Dean Summer (SpeedoThreeSixty).", "version"

所以我准备用纯编码制作一个沙盒游戏,我想在测试代码中为名为
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 <deanlovesmargie@gmail.com>",
    "license": "MIT",
    "bugs": {
        "url": "https://github.com/JavascriptLearner815/SpeedBox/issues"
    },
    "homepage": "https://github.com/JavascriptLearner815/SpeedBox"
}
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:无法在模块索引外使用import语句。js:2Uncaught SyntaxError:意外标记“{”index.js:2Uncaught SyntaxError:意外标识符索引。js:2


我确实有节点,但我不想在本例中使用它。此外,这个问题在过去也发生过。

错误消息有点令人困惑,但您不能在
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);
}
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);
        }
    }
}
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);
}