现在all modern browser support javascript modules , 我正在浏览器中尝试 import
ing 代码。我们可以从 unpkg.com 获取 npm
模块,我找到了 jspm项目,它将 npm
模块包装成浏览器可以使用的格式。
但我仍然遇到问题,最明显的是 RxJS .从版本 6 开始,RxJS 建议您像这样导入构造函数和运算符:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
但是如果我尝试在浏览器中使用:
import { Observable, Subject, ReplaySubject, from, of, range } from 'https://dev.jspm.io/rxjs@6';
import { map, filter, switchMap } from 'https://dev.jspm.io/rxjs@6/operators';
我在这些方面遇到错误:
Uncaught SyntaxError: The requested module 'https://dev.jspm.io/rxjs@6/operators' does not provide an export named 'map'
我可以通过导入整个 rxjs
模块并梳理出我需要的东西来解决这个问题,就像我使用 CDN 一样:
import rxjs from 'https://dev.jspm.io/rxjs@6';
const { Observable } = rxjs;
import operators from 'https://dev.jspm.io/rxjs@6/operators';
const { map } = operators;
但这打败了 Rx 团队试图减少最终包大小等的努力。
我确定这不仅仅是一个 RxJS 问题。
这里有什么解决方案可以让我们的开发 javascript(直接导入浏览器)看起来像我们最终想要传递给 bundler 的东西?
最佳答案
这是一个简单的 rxjs 入门示例 stackblitz:
简而言之:
确保你有一个脚本来添加 rxjs js 文件(例如来自 CDN)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.1.0/rxjs.umd.js">
所有内容都在 rxjs 命名空间下导入,所以对于一个简单的示例用法:
rxjs.of(1, 2, 3)
.subscribe(x => {
const element = document.createElement('div');
element.innerText = 'Data: ' + x;
document.body.appendChild(element)
},
err => { },
() => {
const element = document.createElement('div');
element.innerText = 'All done';
document.body.appendChild(element)
});
关于javascript - 在浏览器中导入 RxJS 6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50308059/