【问题标题】:Uncaught TypeError while importing socket.io in client side Typescript file在客户端 Typescript 文件中导入 socket.io 时未捕获 TypeError
【发布时间】:2022-04-03 00:05:12
【问题描述】:

我有一个使用 express 并用 Typescript 编写的小型 node.js 应用程序。

我正在尝试在客户端 Typescript 文件中使用 socket.io,但尝试加载页面时在浏览器中收到错误消息:

Uncaught TypeError: Error resolving module specifier “socket.io-client”. Relative module specifiers must start with “./”, “../” or “/”.

我的项目正在使用 ES6 模块。我正在尝试在客户端 TS 文件中导入 socket.io,如documentation 所示:

import { io } from "socket.io-client";

我已经使用 NPM 安装了 socket.io 客户端和服务器包。

如果我从编译的 javascript 文件中删除导入并将脚本添加到我的 html 页面,如下所示,它可以正常工作:

<script type="module" src="/javascript/app.js"></script>

但是,如果我从 Typescript 文件中删除导入,它将无法编译,并显示以下消息: error TS2304: Cannot find name 'io'. 引用此行:const socket = io();

我安装的节点包:

├── @tsconfig/node12@1.0.7
├── @types/express@4.17.12
├── @types/node@15.6.1
├── @typescript-eslint/eslint-plugin@4.26.0
├── eslint-config-airbnb-base@14.2.1
├── eslint-config-prettier@8.3.0
├── eslint-plugin-import@2.23.4
├── eslint-plugin-prettier@3.4.0
├── eslint@7.27.0
├── express@4.17.1
├── nodemon@2.0.7
├── prettier@2.3.0
├── socket.io-client@4.1.2
├── socket.io@4.1.2
└── typescript@4.3.2

tsconfig.json:

{
  "extends": "@tsconfig/node12/tsconfig.json",
  "compilerOptions": {
    "outDir": "dist/",
    "rootDir": "src/",
    "lib": ["dom"],
    "module": "esnext",
    "moduleResolution": "node",
    "declaration": true
  },
  "include": ["src/"]
}

package.json:

{
  "name": "jacynth",
  "version": "1.0.0",
  "description": "Jacynth game",
  "main": "dist/server.js",
  "type": "module",
  "scripts": {
    "start": "node server",
    "dev": "nodemon server",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Dylan Cairns",
  "license": "CC-BY-SA-3.0",
  "dependencies": {
    "@types/express": "^4.17.12",
    "express": "^4.17.1",
    "socket.io": "^4.1.2",
    "socket.io-client": "^4.1.2",
    "typescript": "^4.3.2"
  },
  "devDependencies": {
    "@tsconfig/node12": "^1.0.7",
    "@types/node": "^15.6.1",
    "@typescript-eslint/eslint-plugin": "^4.26.0",
    "eslint": "^7.27.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-prettier": "^3.4.0",
    "nodemon": "^2.0.7",
    "prettier": "^2.3.0"
  }
}

任何解决此模块导入问题的帮助将不胜感激。谢谢

【问题讨论】:

    标签: typescript module socket.io client-side


    【解决方案1】:

    看起来它需要一些构建工具才能像这样导入。

    试试这个:

    import { io } from "https://cdn.socket.io/4.4.1/socket.io.esm.min.js"
    

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 2018-07-13
      • 2014-11-25
      • 2018-03-27
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多