javascriptnpmrxjsjspmunpkg

Importing RxJS 6 in browser?


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?


Solution

  • 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/rxjs@6.3.3/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 .

    For now you have to rely on https://jspm.io or make your own bundle (e.g. with rollup as suggested by @Ovidiu Dolha).