无法从 'sockjs-client' 导入(打字稿)

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

我对 angular 和打字稿还很陌生。

首先我通过 npm 安装:

npm install --save sockjs-client

我正在尝试在 chat.component.ts 中这样导入:

import * as SockJS from 'sockjs-client';

但是我收到这个错误:

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

所以之后我按照错误的建议尝试了以下操作:

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

但这只会导致新的警告:

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

这是我的组件的完整代码

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();
  }
}

怎么办?当我启动应用程序时,我得到的只是一个白页和一个控制台错误,提示未定义全局。

请执行以下命令并重试。

npm install --save sockjs-client    
npm install --save @types/sockjs-client

npm audit fix

请添加此声明

declare module 'sockjs-client';

您也可以访问这个link: How to add SockJS into Angular 2 project?

我不知道这是否 'best practice' 但它适合我。

在 index.html 文件中,我只是通过标签加载 SockJS。

然后在我的 chat.component.ts 顶部添加以下内容:

declare var SockJS: any;

实际上,为了打字的好处,您需要导入默认值:

import SockJS from 'sockjs-client';