ws: WebSocket.Server is not a constructor

content is same with title.

I used ‘ws’ module in electron main process not browser.

It work on local environment, but occur error with message ‘WebSocket.Server is not a constructor’ when packaging.

I’m tried to solve this with add external: ['WebSocket', 'WebSocketServer'] in webpack.config.js. but It didn’t work.

anyone who can solve this problem. please, tell me how to solve.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 3
  • Comments: 24 (2 by maintainers)

Most upvoted comments

There is no ws.Server in the ESM version, use import { WebSocketServer } from 'ws' instead.

I’m getting this with ESM:

package.json:

{
  "type": "module",
  "dependencies": {
    "ws": "^8.2.3"
  }
}
import ws from 'ws';

new ws.Server({ port: 8080 });
TypeError: ws.Server is not a constructor

I can confirm the solution by @pyeongoh is working fine. In my case I was using Vue with electron-builder and I had to add the following configuration options to vue.config.js:

module.exports = {
  configureWebpack: {
    resolve: {
      mainFields: ['main', 'browser']
    }
  }
}

Afterwards everything worked as expected.

try this

import WebSocket, { WebSocketServer as WSWebSocketServer } from ‘ws’;

// work with commonjs and esm const WebSocketServer = WebSocket.Server || WSWebSocketServer;

this is still an issue for me:

  • i use ws for testing, so i have it declared as a dev-dependency
  • the error i get is ws_1.Server is not a constructor
  • no webpack or any other bundler in my build
  • downgrading to 7.0.0 fixes the issue

package.json:

  "devDependencies": {
    "@types/ws": "^8.5.4",
    "typescript": "^5.0.4",
    "ws": "^8.13.0" // also tried e.g. '^8.5.4'
  }

tsconfig.json:

{
   "compilerOptions": {
      "target": "es5",                         
      "module": "commonjs"
   }
}

my.test.ts:

import {Server} from "ws"

const port = 1337
const srv = new Server({port})

Error:

ws_1.Server is not a constructor
TypeError: ws_1.Server is not a constructor

I have encountered this problem when building an electron project and other solutions did not work for me.

the message ws does not work in the browser. Browser clients must use the native

comes from the file ./node_modules/ws/browser.js because either electron or ws thinks you are in a browser.

the fix that will work for all is to just change the line "browser": "browser.js", in ./node_modules/ws/package.json to "browser": "index.js", or just delete it . then the error wont show up because even if it thinks you are running in a browser it will still load the index.js main file