【问题标题】:Can not import from 'sockjs-client' (typescript)无法从“sockjs-client”(打字稿)导入
【发布时间】:2022-02-03 00:35:12
【问题描述】:

我对 angular 和 typescript 很陌生。

首先我通过 npm 安装:

npm install --save sockjs-client

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

import * as SockJS from 'sockjs-client';

但我收到此错误:

TS7016:找不到模块“sockjs-client”的声明文件。 '/home/simon/javaprojs/tour-creator/client/node_modules/sockjs-client/lib/entry.js' 隐含地具有“任何”类型。尝试npm i --save-dev @types/sockjs-client(如果存在)或添加新声明 (.d.ts) 包含declare module 'sockjs-client';的文件

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

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

但这只会导致新的警告:

警告: /home/simon/javaprojs/tour-creator/client/src/app/components/chat/chat.component.ts 取决于'sockjs-client'。 CommonJS 或 AMD 依赖项可能导致 优化救助。有关更多信息,请参阅: 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();
  }
}

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

【问题讨论】:

    标签: angular typescript npm sockjs


    【解决方案1】:

    请执行以下命令,然后重试。

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

    请添加此声明

    declare module 'sockjs-client';
    

    您也可以访问此链接: How to add SockJS into Angular 2 project?

    【讨论】:

    • 我今天晚些时候试试,谢谢你的回答
    • 请先卸载@types/sockjs-client。今天对我有用
    • 这并没有解决我的问题。我仍然在构建时收到此警告:警告:/home/simon/javaprojs/tour-creator/client/src/app/components/chat/chat.component.ts 取决于“sockjs-client”。 CommonJS 或 AMD 依赖项可能会导致优化救助。有关详细信息,请参阅:angular.io/guide/build#configuring-commonjs-dependencies 应用程序启动时出现空白页和控制台错误
    • 但我为我工作。让我们尝试挖掘北斗。如果我能找到任何东西,会通知你。
    • 我尝试删除我的 node_modules 文件夹,并执行您建议的 3 个步骤。但没有运气
    【解决方案2】:

    我不知道这是否是“最佳做法”,但它对我有用。

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

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

    declare var SockJS: any;
    

    【讨论】:

      【解决方案3】:

      实际上,为了便于输入,您需要导入默认值:

      import SockJS from 'sockjs-client';
      

      【讨论】:

        猜你喜欢
        • 2015-09-17
        • 1970-01-01
        • 2021-02-03
        • 2021-11-11
        • 1970-01-01
        • 2018-04-26
        • 2019-11-10
        • 1970-01-01
        • 2019-09-30
        相关资源
        最近更新 更多