Search code examples
angulartypescriptnpmsockjs

Can not import from 'sockjs-client' (typescript)


I am very new to angular and typescript.

First I install via npm:

npm install --save sockjs-client

I am trying to import like this in chat.component.ts:

import * as SockJS from 'sockjs-client';

But I am getting this error:

TS7016: Could not find a declaration file for module 'sockjs-client'. '/home/simon/javaprojs/tour-creator/client/node_modules/sockjs-client/lib/entry.js' implicitly has an 'any' type.   Try npm i --save-dev @types/sockjs-client if it exists or add a new declaration (.d.ts) file containing declare module 'sockjs-client';

So after that I tried the following as suggested by the error:

npm i --save-dev @types/sockjs-client

But that only resulted in a new warning:

Warning: /home/simon/javaprojs/tour-creator/client/src/app/components/chat/chat.component.ts depends on 'sockjs-client'. CommonJS or AMD dependencies can cause optimization bailouts. For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

Here is the full code of my component

import {Component, OnInit} from '@angular/core';

import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css'],
})
export class ChatComponent implements OnInit {

  constructor() { }

  connect(): void {
    const socket = new SockJS('gs-guide-websocket');
  }

  ngOnInit(): void {
    this.connect();
  }
}

What to do? When I start the application, all I get is a white page, and a console error saying that global is not defined.


Solution

  • I don't know if this is 'best practice' but it works for me.

    In the index.html file I simply load SockJS via tag.

    And then in top of my chat.component.ts I add the following:

    declare var SockJS: any;