[英]TypeScript typings give me "index.d.ts is not a module"
我得到File node_modules/@types/webrtc/index.d.ts is not a module with this code:
import * as webrtc from "webrtc";
const peerConnection1 = new RTCPeerConnection();
我已经使用npm i @types/webrtc --save-dev
安装了类型。 在const peerConnection1 = new RTCPeerConnection();
中悬停在RTCPeerConnection
上; 在 Visual Studio Code 中显示类型注释,因此至少代码编辑器可以看到类型。 运行tsc
(或webpack
与ts-loader
)失败并出现错误。
I have tried npm i webrtc --save
in a misguided attempt for solving this, but it did not change anything and I really only want the typings anyway, WebRTC is right there in the browser, I don't need a package for that. (支持一边。)
index.d.ts
文件确实不是一个模块,它只是引用了另外两个带有接口的文件。 所以我想import * as webrtc from "webrtc";
希望打字仍然能被tsc
以某种方式看到。 (但这是不可能的,因为我在 TypeScript 配置文件中排除了node_modules
。)当我这样做时,不再识别RTCPeerConnection
。
添加/// <reference src="node_modules/@types/webrtc/" />
没有帮助, tsc
说Invalid reference directive syntax 。
您可以在 GitLab 上查看具有最少复制的存储库。 我不太精通 TypeScript 类型的获取,所以如果我要解决这一切都错了,请原谅我的无知。
webrtc 是浏览器的一部分; 您正在尝试导入模块。 只需导入(类型)库:
import "webrtc";
您可能需要在编译器选项中使用"moduleResolution": "node"
。
或者使用"types": ["webrtc"]
编译器选项,编译器会自动为您加载这些类型。
你可能想添加
"types": ["webrtc"]
到您的tsconfig.json
,或者更不tsconfig.json
使用
/// <reference types="webrtc" />
在您的源文件中。 这是tsconfig.json
的一个示例:
{
"compilerOptions": {
"target": "es5",
"sourceMap": true,
"noImplicitAny": true,
"types": ["webrtc"]
},
"exclude": [
"node_modules"
]
}
这告诉 TypeScript 它应该在你的构建中包含webrtc
声明
另一种选择是在您的模块中添加一个新的声明文件*.d.ts
,即:
declare module 'my-module';
无需导入任何东西,运行以下命令:
npm install --save @types/webrtc
更新 tsconfig.json -
“类型”:[“@types/webrtc”]
/// <reference types="@types/<your_types_module>" />
根据您的构建和样式需求,您可能想也可能不想这样做,但这似乎是快速(和肮脏)的解决方法。
在我的情况下,它是一个损坏的依赖项,删除模块和npm install
完成了工作。
就我而言,我收到此错误消息, index.d.ts
包含由 TypeScript 编译器生成的index.d.ts
文件。
问题是我忘记在源.ts
文件中指定任何import
或export
声明。 我在从.js
移植到.ts
时删除了原来的module.export = {…}
位,但还没有替换它。
这是文档定义“模块”的方式(强调):
在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级导入或导出的文件都被视为模块。 相反,没有任何顶级导入或导出声明的文件被视为脚本,其内容在全局范围内可用(因此也对模块可用)。
向我打算export
的内容添加导出将index.d.ts
转换为模块,清除错误。
在 vscode 中
Ctrl + p > 开发人员:重新加载窗口
我在 VS 代码编辑器上遇到了类似的错误。 简单地说,关闭和打开 VSCode 再次为我解决了这个问题。
使用要求
const webRtc = require('webrtc');
你导入应该没问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.