Importing RxJS 6 in browser?
The es6 module export syntax is inside the subfolder _esm2015
. So you need to import:
import { Observable, Subject, ReplaySubject, from, of, range } from 'https://dev.jspm.io/rxjs@6/_esm2015';
import { map, filter, switchMap } from 'https://dev.jspm.io/rxjs@6/_esm2015/operators';
Sadly you can't just install rxjs with npm install rxjs@6
and then import
in the browser, because the distribution source is missing the file extension .js
in the import
statements: https://unpkg.com/@reactivex/[email protected]/dist/esm2015/index.js.
But the browser needs the file extensions for import
(at the moment): (https://developers.google.com/web/fundamentals/primers/modules#specifiers):
// Not supported (yet):
import {shout} from 'jquery';
import {shout} from 'lib.mjs';
import {shout} from 'modules/lib.mjs';
// Supported:
import {shout} from './lib.mjs';
import {shout} from '../lib.mjs';
import {shout} from '/modules/lib.mjs';
import {shout} from 'https://simple.example/modules/lib.mjs';
There is also an issue for this: https://github.com/ReactiveX/rxjs/issues/4416 .
- Sidenote: https://dev.jspm.io/rxjs@6/_esm2015 will resolve to https://dev.jspm.io/rxjs@6/_esm2015/index.js
For now you have to rely on https://jspm.io or make your own bundle (e.g. with rollup as suggested by @Ovidiu Dolha).
Here's a simple rxjs starter example stackblitz:
- https://stackblitz.com/edit/js-gm1qso
In short:
Make sure you have a script to add the rxjs js file (for example from a CDN)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.1.0/rxjs.umd.js">
Everything is imported under the rxjs namespace, so to a simple example usage:
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)
});