TypeScript打字给我"index.d.ts不是一个模块"

Tom*_*uer 34 typescript typescript-typings

我收到文件node_modules/@types/webrtc/index.d.ts不是带有此代码的模块:

import * as webrtc from "webrtc";
const peerConnection1 = new RTCPeerConnection();
Run Code Online (Sandbox Code Playgroud)

我已经安装了打字机npm i @types/webrtc --save-dev.将鼠标悬停在Visual Studio代码RTCPeerConnection中的const peerConnection1 = new RTCPeerConnection();显示类型注释中,以便至少代码编辑器可以看到类型.运行tsc(或webpackwith ts-loader)失败并显示错误.

我试图npm i webrtc --save以误导的方式解决这个问题,但它没有改变任何东西,我真的只想要打字,WebRTC就在浏览器中,我不需要一个包.(支持旁边.)

index.d.ts文件确实不是一个模块,它只引用其中包含接口的其他两个文件.所以我想删除import * as webrtc from "webrtc";希望打字仍然可以以tsc某种方式显示.(但这是不可能的,因为我node_modules在TypeScript配置文件中排除.)当我这样做时,RTCPeerConnection不再被识别.

添加/// <reference src="node_modules/@types/webrtc/" />没有帮助,tsc无效的引用指令语法.

您可以在GitLab上查看具有最少repro的存储库.我不太熟悉TypeScript打字收购,所以请原谅我的无知,如果我说这一切都错了.

tay*_*lıç 141

在 vscode 中

Ctrl+ Shift+ p > 开发人员:重新加载窗口。

  • 非常感谢您的回答!为什么这可以工作而重新启动 vsCode 却不起作用? (8认同)

Mei*_*hes 44

webrtc是浏览器的一部分; 你正试图导入一个模块.只需导入(打字)库:

import "webrtc";
Run Code Online (Sandbox Code Playgroud)

您可能需要"moduleResolution": "node"在编译器选项中使用.

或者使用"types": ["webrtc"]编译器选项,编译器将自动为您加载这些类型.


Dan*_*ser 9

你可能想要添加

"types": ["webrtc"]
Run Code Online (Sandbox Code Playgroud)

对你的tsconfig.json,或不太优选使用

/// <reference types="webrtc" />
Run Code Online (Sandbox Code Playgroud)

在您的源文件中.以下是您的示例tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "noImplicitAny": true,

        "types": ["webrtc"]
    },
    "exclude": [
        "node_modules"
    ]
}
Run Code Online (Sandbox Code Playgroud)

这告诉TypeScript它应该包含webrtc构建中的声明

  • 不要设置`types`,否则*只有*那些类型会被加载——通常`node_modules/@types`中的所有内容都会被加载,这将阻止这种行为。这些天你只需要`npm i @types/webrtc`。 (3认同)

小智 6

无需导入任何东西,运行以下命令:

  1. npm install --save @types/webrtc
  2. 更新 tsconfig.json -

    “类型”:[“@types/webrtc”]

  • 这将使得仅导入 webrtc 类型。不要更新 tsconfig.json。 (4认同)
  • `npm install --save-dev @types/...` 是首选 - 通常,TS 不在生产中使用 (2认同)

Kar*_*ius 5

另一种选择是*.d.ts在模块中添加一个新的声明文件,即:

declare module 'my-module';
Run Code Online (Sandbox Code Playgroud)