简体   繁体   中英

Uncaught SyntaxError: Cannot use import statement outside a module when I export and import a class

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 <deanlovesmargie@gmail.com>",
    "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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM