Importing RxJS 6 in browser?

nicholas picture nicholas · May 12, 2018 · Viewed 10.2k times · Source

Now that all modern browser support javascript modules, I'm trying out importing code right in the browser. We can get npm modules from unpkg.com, and I've found the jspm project, which wraps npm modules into a format that can be consumed by the browser.

But I'm still having problems, most notably with RxJS. RxJS, as of version 6, recommends you import constructors and operators like this:

import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';

But if I try to do that in the browser with:

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';

I get errors along these lines:

Uncaught SyntaxError: The requested module 'https://dev.jspm.io/rxjs@6/operators' does not provide an export named 'map'

I can get around it by importing the whole rxjs module and teasing out what I need, like I would using a 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;

but this defeats what the Rx team is trying to do to decrease the final bundle size, etc.

I'm sure this isn't just an RxJS problem.

What is the solution here moving forward to get our dev javascript (imports directly into the browser) to look like what we'd finally want to pass to a bundler?

Answer

Chris White picture Chris White · May 13, 2018

Here's a simple rxjs starter example stackblitz:

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)
  });