外部脚本无法在 html 文件中工作,请问我做错了什么

问题描述 投票:0回答:1

我有下面的 game.mjs 文件和以下代码

import Player from './Player.mjs';
import Collectible from './Collectible.mjs';

const socket = io();
const canvas = document.getElementById('game-window');
const context = canvas.getContext('2d');

const load = () => {
  context.fillStyle = "#000000";
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.font = "30px Comic Sans MS";
  context.fillStyle = "red";
  context.textAlign = "center";
  context.fillText("Coin Race", 100, 30);
  context.strokeStyle = "yellow";
  context.strokeRect(5, 35, canvas.width - 10, canvas.height - 40)
}

load();

我在index.html文件中有以下内容

<!DOCTYPE html>
<html>
  <head>
    <title>Secure Real-Time Multiplayer Game</title>
    <meta
      name="description"
      content="An example for the fCC InfoSec Secure Real-Time Multiplayer Game project"
    />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="../public/style.css" type="text/css" />
    <link href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap" rel="stylesheet">
    <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <header>
      <h1>Secure Real Time Multiplayer Game</h1>
    </header>
    <hr style="margin: 25px" />
    <div class="container">
      <canvas 
        ref="game"
        id="game-window" 
        width="640" 
        height="480"
      >
      </canvas>
    </div>
  </body>
 <script src="../public/game.mjs" type="module"></script>
</html>

外部文件不使用脚本标签运行,但如果我将代码直接添加到脚本标签中的 html 文件中,它就可以工作。

有人可以告诉我我做错了什么吗?

我注意到当我在 game.mjs 中注释掉以下内容时,外部脚本会运行

import Player from './Player.mjs';
import Collectible from './Collectible.mjs';

const socket = io();

谢谢你

javascript html typescript
1个回答
0
投票

我将 server.js 文件中的

app.listen
更改为
http.listen
,现在工作正常。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.