沉冰浮水

沉冰浮水

做最终到的事,成为最终成为的人!
github
bilibili
mastodon
zhihu
douban

"Da Keng" is about how to correctly import WebSocketServer under the module pattern.

WebSocket.Server is not a constructor

Encountered the above error, tried changing the syntax from cjs to mjs in module mode, but it didn't work;

import WebSocket from "ws"
console.log(typeof WebSocket)
console.log(typeof WebSocket.Server)
// function
// undefined

Using the error message "WebSocket.Server is not a constructor" as a keyword didn't help me find the reason;

Until I tried a different approach, directly searching for "import WebSocket from 'ws'", and got the following code:

import WebSocket, { WebSocketServer } from 'ws';
console.log(typeof WebSocket)
console.log(typeof WebSocketServer)
// function
// function

Then I looked at the export file of the ws library;

// cjs
'use strict';

const WebSocket = require('./lib/websocket');

WebSocket.createWebSocketStream = require('./lib/stream');
WebSocket.Server = require('./lib/websocket-server');
WebSocket.Receiver = require('./lib/receiver');
WebSocket.Sender = require('./lib/sender');

WebSocket.WebSocket = WebSocket;
WebSocket.WebSocketServer = WebSocket.Server;

module.exports = WebSocket;
// mjs
import createWebSocketStream from './lib/stream.js';
import Receiver from './lib/receiver.js';
import Sender from './lib/sender.js';
import WebSocket from './lib/websocket.js';
import WebSocketServer from './lib/websocket-server.js';

export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };
export default WebSocket;

The difference is quite significant, isn't it Orz;

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.