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

时间:2021-03-07 22:40:26

标签: angular typescript npm sockjs

我对 angular 和 typescript 很陌生。

首先我通过 npm 安装:

<Pressable style={({ pressed }) => [
      {
        backgroundColor: pressed ? 'rgb(210, 230, 255)' : 'white', 
        flex: 1,
      },
    ]} cancelable={false} onPressIn={() => console.log('pressin')} onPress={() => console.log('press')}>
       {({ pressed }) => ( 
    <View style={{flex: 1, width: ScreenWidth }}
      onStartShouldSetResponderCapture = { (e) => { return false}}
      >
      
        <WebView
                ref={webview}
                javaScriptEnabled={true}
                bounces={false}
                onShouldStartLoadWithRequest={() => true}
                javaScriptEnabledAndroid={true}
                startInLoadingState={true}
                originWhitelist={['*']}
                source={{ html: htmltext}}
                style={{margin:5}}
                onMessage={event => {
                  let jsonValue = JSON.parse(event.nativeEvent.data);
                  console.log('Pages:', event.nativeEvent.data);
                }}
              />
              </View>
              )}
              
              </Pressable>

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

npm install --save sockjs-client

但我收到此错误:

<块引用>

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

的文件

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

declare module '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

这是我的组件的完整代码

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

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

2 个答案:

答案 0 :(得分:0)

请执行以下命令并重试。

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?

答案 1 :(得分:0)

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

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

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

declare var SockJS: any;