【问题标题】:Typescript with rxjs带有 rxjs 的打字稿
【发布时间】:2018-10-26 12:24:47
【问题描述】:

我目前正在处理一个没有任何模块加载器的打字稿项目。

现在我正在尝试将 rxjs 集成到我的项目中。但我每次都会收到错误ReferenceError: exports is not defined。是否有必要使用模块加载器,如果是的话,你能帮我设置它吗?我目前正在用tsc -w编译ts文件

Main.ts

const mock = of('Hello');
mock.subscribe(res => console.log(res));

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>HM</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="assets/hm-logo.png">
    <link rel="stylesheet" type="text/css" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<script src="./main.js"></script>
</body>
</html>

【问题讨论】:

  • 你是如何将 rxjs 添加到你的项目中的?
  • 带 npm,使用版本 rxjs: 6.3.1
  • 查看 npm 文档,节点包似乎是特定于 CommonJS 使用的。 CDN 版本似乎正在定义一个全局 rxjs 对象。您应该能够在没有任何模块的情况下使用它。 npmjs.com/package/rxjs

标签: typescript rxjs es6-module-loader


【解决方案1】:

感谢@toskv,我设法在没有任何模块加载器的情况下将 rxjs 集成到 typescript。为此,我需要考虑以下步骤:

1.步骤

将cdn链接添加到根HTML(在head标签内),如下所示:

<script src="https://unpkg.com/rxjs@6.3.3/bundles/rxjs.umd.min.js"></script>

2.步骤

添加一个带有全局变量的 rxjs.d.ts 文件:

declare var rxjs;

3.步骤

在 tsconfig.json 文件中包含 rxjs.d.ts 文件,如:

  "include": [
    "src/**/*",
    "rxjs.d.ts"
  ]

4.步骤

现在您可以在 ts 文件中使用 rxjs,例如:

const { Observable, Subject, ReplaySubject, from, of, range } = rxjs;
const { map, filter, switchMap } = rxjs.operators;

range(1, 200)
    .pipe(filter(x => x % 2 === 1), map(x => x + x))
    .subscribe(x => console.log(x));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 2018-10-16
    • 2018-12-07
    相关资源
    最近更新 更多