使用 UMD 构建时如何将 RxJS 与类型定义一起使用? [英] How do use RxJS with type definitions when using the UMD build?
问题描述
例如:
- npm i @reactivex/rxjs
- 使用一些使用 RxJs 的函数创建一个 index.ts 文件
- 创建一个 index.html 文件,引用 RxJs UMD 构建和由 typescript 编译器从 index.ts 创建的 index.js 文件一个.
这里有一个重现:https://github.com/valeriob/Repro_rxjs_typescript只需运行tsc"并查看编译错误.
here there is a repro : https://github.com/valeriob/Repro_rxjs_typescript Just run "tsc" and see the compiling error.
在这种情况下如何在编辑 index.ts 时获取类型定义?
How do i get type definitions while editing index.ts in this scenario ?
遵循这些指南 https://github.com/zspitz/TypeScript-Handbook/blob/release-2.0/pages/Modules.md#umd-modules我能够通过附加作为命名空间 rxjs 导出"来使其工作;到文件 node_modules/rxjs/index.d.ts .
Following those guidelines https://github.com/zspitz/TypeScript-Handbook/blob/release-2.0/pages/Modules.md#umd-modules i was able to make it work by appending "export as namespace rxjs;" to the file node_modules/rxjs/index.d.ts .
如果这应该是解决方案,应该由图书馆作者完成吗?
If this should be the solution, should it be done by the library authors ?
推荐答案
我设法找到了一种解决方法,因为 rxjs 没有为其 UMD 包构建类型定义.
I managed to find a workaround, since rxjs does not build with type definitions for its UMD bundle.
首先,这仅适用于 TS >= 3.5,因为您必须打开 allowUmdGlobalAccess,否则它会给你这个错误:
First of all, this only works for TS >= 3.5, because you have to switch on allowUmdGlobalAccess, or else it will give you this error:
TS2686: 'rxjs' 指的是一个 UMD 全局,但当前文件是一个模块.考虑改为添加导入.
TS2686: 'rxjs' refers to a UMD global, but the current file is a module. Consider adding an import instead.
通过检查文件node_modules/rxjs/bundles/rxjs.umd.js
的末尾,可以发现operators,testing、ajax、webSocket 和 fetch 就像子命名空间,其他的一切都直接在全局 rxjs
下:>
By inspecting the end of the file node_modules/rxjs/bundles/rxjs.umd.js
, you can find that operators, testing, ajax, webSocket and fetch are like subnamespaces, and everything else is directly under the global rxjs
:
...
var operators = _operators;
var testing = _testing;
var ajax$1 = _ajax;
var webSocket$1 = _webSocket;
var fetch$1 = _fetch;
exports.operators = operators;
exports.testing = testing;
exports.ajax = ajax$1;
exports.webSocket = webSocket$1;
exports.fetch = fetch$1;
exports.Observable = Observable;
exports.ConnectableObservable = ConnectableObservable;
exports.GroupedObservable = GroupedObservable;
exports.observable = observable;
...
所以你所要做的就是创建一个 .d.ts 文件,如下所示:
So all you have to do is create a .d.ts file like this:
export * from 'rxjs'
export * as operators from 'rxjs/operators'
export * as testing from 'rxjs/testing'
export * as ajax from 'rxjs/ajax'
export * as webSocket from 'rxjs/webSocket'
export * as fetch from 'rxjs/fetch'
export as namespace rxjs
现在您可以在任何 ts 文件中使用全局 rxjs
:
And now you can use the global rxjs
in any of you ts files:
const { interval } = rxjs
const { filter } = rxjs.operators
interval(500).pipe(
filter(t => t % 2 === 0)
).subscribe(t => console.log(t))
这篇关于使用 UMD 构建时如何将 RxJS 与类型定义一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!