沉冰浮水

沉冰浮水

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

「大坑」關於 module 模式下如何正確引入 WebSocketServer

WebSocket.Server 不是一個構造函數

遇到上述錯誤時,直接按照 cjs 的寫法改成 mjs 形式,但是無法使用;

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

以報錯的「WebSocket.Server 不是一個構造函數」作為關鍵詞並未找到原因;

直到我換了個方式,直接搜索「import WebSocket from 'ws'」,得到的程式碼如下:

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

然後我去看了 ws 這個庫的導出文件;

// 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;

差異不僅僅是有點大好嗎 Orz;

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。