如何在用于服务器构建的 polymer 3 PWA 初学者工具包应用程序中导入 socket.io.client javascript

How to import socket.io.client javascript in polymer 3 PWA starter kit app for server build

我在我的 Web 组件中使用 socket.io-客户端连接,需要导入 socket.io-客户端 java 库 (socket.io-client github)。

Usage in web-component: var socket =  io.connect(socket_url);

所有导入 socket.io-client.js 的方法都失败了,直接在我的 Web 组件中使用不同的导入变体,如下所示:

import io from 'socket.io-client'

我搜索并发现(solution)socket.io-client 没有提供 polymer 导入所需的 ES 模块。从此答案中提出的解决方案建议将 socket.io java 脚本直接包含在主 index.html 中。所以我现在在我的 index.html 中导入 socket.io-client 脚本

<script src="node_modules/socket.io-client/dist/socket.io.slim.js" crossorigin></script>

此解决方案适用于开发和测试:

npm start

构建工作正常,应用程序和套接字实现在浏览器中按预期在 http://127.0.0.1:8081 工作。

但是当我开始构建生产过程并使用时:

npm run build:prpl-server
npm run serve:prpl-server
...
prpl-server listening http://127.0.0.1:8080

构建成功但应用程序在浏览器中运行失败,控制台出现以下错误:

Loading failed for the with source “http://127.0.0.1:8080/es6-bundled/node_assets/socket.io-client/dist/socket.io.slim.js”.

因此 socket.io...js 文件在构建过程中不会 put/copied 进入构建文件夹。构建目录中甚至没有 node_assets 文件夹。但是代码和测试工作正常——所以导入和脚本似乎工作正常。我在最终版本中做错了什么,但不明白是什么。

所以问题是如何在index.html或web组件中正确导入socket.io-client java脚本,以将其正确输出到最终构建中?

我认为您需要将 "node_modules/socket.io-client/dist/**" 添加到 polymer.json 的 extraDependencies 部分,以便构建过程考虑文件

看起来像这样

{
  "extraDependencies": [
    "manifest.json",
    "node_modules/@webcomponents/webcomponentsjs/**",
    "push-manifest.json",
    "node_modules/socket.io-client/dist/**"
  ]
}