Installation and Setup

The content for this chapter is taken from the offical docs but I am trying to provide you with a little more information as to why and also its nice to have everything in one place. Official docs

TH Rxjs lib can be consumed in many different ways, namely ES6, CommonJS and as ES5/CDN.

ES6

Install

  1. npm install rxjs

Setup

  1. import Rx from 'rxjs/Rx';
  2. Rx.Observable.of(1,2,3)

GOTCHA

This statement import Rx from 'rxjs/Rx' utilizes the entire library. It is great for testing out various features but once hitting production this is a bad idea as Rxjs is quite a heave library. In a more realistic scenario you would want to use the alternate approach below that only imports the operators that you actually use :

  1. import { Observable } from 'rxjs/Observable';
  2. import 'rxjs/add/observable/of';
  3. import 'rxjs/add/operator/map';
  4. let stream$ = Observable.of(1,2,3).map(x => x + '!!!');
  5. stream$.subscribe((val) => {
  6. console.log(val) // 1!!! 2!!! 3!!!
  7. })

CommonJS

Same install as with ES6

Install

  1. npm install rxjs

Setup

Setup is different though

Below is yet again showcasing the greedy import that is great for testing but bad for production

  1. var Rx = require('rxjs/Rx');
  2. Rx.Observable.of(1,2,3); // etc

And the better approach here being:

  1. let Observable = require('rxjs/Observable').Observable;
  2. // patch Observable with appropriate methods
  3. require('rxjs/add/observable/of');
  4. require('rxjs/add/operator/map');
  5. Observable.of(1,2,3).map((x) => { return x + '!!!'; }); // etc

As you can see require('rxjs/Observable') just gives us the Rx object and we need to dig one level down to find the Observable.

Notice also we just require('path/to/operator') to get the operator we want to import for our app.

CDN or ES5

If I am on neither ES6 or CommonJS there is another approach namely:

  1. <script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

Notice however this will give you the full lib. As you are requiring it externally it won’t affect your bundle size though.