0

I am trying to add the ws npm library to my Angular Project but can't figure out how to do it correctly.

I have installed it using npm install ws. Now I am trying to import it in the app.module.ts file.

I've tried import { WebSocket } from 'ws'; and in imports I've added WebSocket.

I've also tried other form of writing it and they all give me an error: 'WebSocket' can only be imported by turning on the 'esModuleInterop' flag and using a default import.

Removing the line import { WebSocket } from 'ws'; and leaving WebSocket in the imports list seems to be okay. But I think that this is the wrong WebSocket because I don't see anything related to the ws library.

Is this alright or am I doing something wrong?

I was taking a look at Sending and receiving text data in this tutorial https://www.npmjs.com/package/ws#sending-and-receiving-text-data for them it seems to work.

Royi Levy
  • 513
  • 1
  • 3
  • 14

1 Answers1

0

You can not import your library into an Angular module, Angular module is a very specific architecture look at it here https://angular.io/guide/architecture-modules. You can use this library directly into a component or a service, in my opinion, you want to create a websocket.service.ts that will reference the library, and you will create some method around it.

Crawling quickly the web you can find an easy example here https://javascript-conference.com/blog/real-time-in-angular-a-journey-into-websocket-and-rxjs/ that demonstrates the concept.

zagoa
  • 798
  • 4
  • 23
  • Okay, I tried doing `import { WebSocket } from 'ws';` in a new `websocket.service.ts`. But I still get `'WebSocket' can only be imported by turning on the 'esModuleInterop' flag and using a default import.`. – Royi Levy Aug 30 '21 at 13:36
  • Please do some research before posting https://stackoverflow.com/questions/56238356/understanding-esmoduleinterop-in-tsconfig-file – zagoa Aug 30 '21 at 13:37