【发布时间】:2020-10-22 14:16:06
【问题描述】:
我正在尝试使用 npm typescript @types/socket.io 定义。 要安装,我只需:
npm install --save @types/socket.io
npm install --save socket.io
这将我的 package.json 更新为如下所示:
...
"devDependencies": {
"@types/socket.io": "^2.1.8",
"socket.io": "^2.3.0"
}
在我的 TS 文件中,我尝试:
// client.ts
// this file is compiled to js with tsc like so: tsc client.ts
import IO from 'socket.io';
let socket = IO("http://localhost:3030");
socket.emit("message", "HELLO!");
我的 index.html 是:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<script type="module" src="client.js"></script>
</head>
</html>
用于托管 html 的 python 服务器:
#server.py
import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
Handler.extensions_map = {
'.manifest': 'text/cache-manifest',
'.html': 'text/html',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.svg': 'image/svg+xml',
'.css': 'text/css',
'.js': 'application/x-javascript',
'': 'application/wasm', # Default
}
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
在浏览器控制台中抛出这个:
Uncaught TypeError: Failed to resolve module specifier "socket.io". Relative references must start with either "/", "./", or "../".
我目前看到我的当前路径中有一个 node_modules 文件夹以及包含 socket.io 定义的 @types 子文件夹。我在 node_modules 下也有常规的 socket.io js 文件夹。 Typescript 编译一切都很好,没有错误。
我认为在执行 npm install @types/ 之后,typescript 会巧妙地使用已安装的包而无需任何进一步的调整。
我的 tsconfig.json 看起来像:
{
"compilerOptions": {
"target": "ES6",
"module": "ES6",
"outDir": "out",
"sourceMap": true,
"watch": true,
"strictNullChecks": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"esModuleInterop": true,
"allowJs": true,
}
}
package.json:
{
"dependencies": {
"@types/express": "^4.17.6",
"express": "^4.17.1",
"typescript": "^3.9.6"
},
"devDependencies": {
"@types/socket.io": "^2.1.8",
"socket.io": "^2.3.0"
},
"type": "module"
}
谁能给我一些关于我可能做错了什么的想法?我是否错误地使用了 socket.io?我是否错误地导入了 socket.io?我 npm install socket.io @types 不正确吗?我的打字稿设置错了吗?
【问题讨论】:
-
您好,运行文件可能有问题。你的开发脚本是什么?
-
添加了我的开发文件。
-
在您的
package.json中应该有一个scripts部分,您可以通过npm run command运行您是否也可以添加这些部分。你如何在你的终端上运行你的服务器? -
它只是一个标准的 python http 服务器。我像这样运行服务器:python server.py
-
我还添加了我的 package.json。我没有任何“脚本”部分
标签: node.js typescript npm websocket socket.io