Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Help] 在electron中建立一个websocket的服务 #442

Open
JimmingSong opened this issue Nov 16, 2023 · 2 comments
Open

[Help] 在electron中建立一个websocket的服务 #442

JimmingSong opened this issue Nov 16, 2023 · 2 comments
Labels
help wanted Extra attention is needed

Comments

@JimmingSong
Copy link

我的需求是要在electron中建立一个websocket的后端服务,
我使用的是koa+koa-websocket我的目录结构是
|-electron
|--server
|----app.js

import Koa from 'koa';
import websock from 'koa-websocket';

const app = websock(new Koa());

app.listen(3000, () => {
    console.log('websocket server listening on port 3000');
})

然后再主进程文件main.ts中引入该文件,但是报如下错误

App threw an error during load
TypeError: WebSocketServer is not a constructor
    at KoaWebSocketServer.listen (D:\workspace\chat-task\dist-electron\main.js:16700:17)
    at Application.listen2 [as listen] (D:\workspace\chat-task\dist-electron\main.js:16738:13)
    at Object.<anonymous> (D:\workspace\chat-task\dist-electron\main.js:16746:5)
    at Module._compile (node:internal/modules/cjs/loader:1271:14)
    at Object..js (node:internal/modules/cjs/loader:1326:10)
    at Module.load (node:internal/modules/cjs/loader:1126:32)
    at node:internal/modules/cjs/loader:967:12
    at Function._load (node:electron/js2c/asar_bundle:2:13327)
    at loadApplicationPackage (D:\workspace\chat-task\node_modules\electron\dist\resources\default_app.asar\main.js:121:16)
    at Object.<anonymous> (D:\workspace\chat-task\node_modules\electron\dist\resources\default_app.asar\main.js:233:9)

我在dist-electron下的main.js文件中找到

var browser = function() {
  throw new Error(
    "ws does not work in the browser. Browser clients must use the native WebSocket object"
  );
};
const url = require$$0$6;
const https = require$$1$5;
const compose = koaCompose;
const co = co_1;
const ws = browser;
const WebSocketServer = ws.Server;

请问我该怎么解决

@JimmingSong JimmingSong added the help wanted Extra attention is needed label Nov 16, 2023
@qq10137383
Copy link

把这个包从devDependencies移动到dependencies试试,我之前用ws的包也是报ws does not work in the browser. Browser clients must use the native WebSocket object,用alias指定为入口也不行,报其他错误,最后修改为dependencies就好了。

@caoxiemeihao
Copy link
Member

把这个包从devDependencies移动到dependencies试试,我之前用ws的包也是报ws does not work in the browser. Browser clients must use the native WebSocket object,用alias指定为入口也不行,报其他错误,最后修改为dependencies就好了。

对的,这样子 import 语句会直接编译成 require
这个问题在 express 上也碰到过,后面有时间看看怎么处理它

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

3 participants