如何让 socket.io 使用 ES6 导入模块?

How to get socket.io working with ES6 import modules?

我将 socket.io 的一个简单示例从 CommonJS require 语法重构为 ES6 import 语法但是当我启动服务器并访问网站时,虽然它显示 HTML 文本(“测试来自 server.js”),它不会通知服务器它已连接。

然而控制台中根本没有错误,它只是表现得好像 socket.io 根本没有加载。

在我的 package.json 文件中,为了让 ES6 模块在 Node 中工作,我有以下条目:

"type": "module",

为什么 socket.io 不起作用?

server.js

import path from 'path';
import http from 'http';
import express from 'express';
import { Server as socketIO } from 'socket.io';

const app = express();
const PORT = 5011;
const __dirname = path.resolve(path.dirname(''));
const server = http.Server(app);
const io = new socketIO(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', (socket) => {
    console.log('user connected');
    socket.emit('greeting-from-server', {
        greeting: 'you loaded the page'
    });
})

app.listen(PORT, () => {
    console.log(`listening on port http://localhost:${PORT}`);
});

/public/index.html

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Socket.IO</title>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io('http://localhost:5011');
        socket.on('greeting-from-server', (data) => {
            console.log(data);
            socket.emit('greeting-from-client', {
                greeting: 'Hello Server'
            });
        });
    </script>
</head>

<body>
    test from server.js
</body>

</html>
import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  // ...
});

io.on("connection", (socket) => {
  // ...
});enter code here

httpServer.listen(3000);