How to bring RxJS 6 into your browser?

With the widespread support for JavaScript modules in all modern browsers, I am experimenting with importing code directly in the browser using import. Utilizing unpkg.com for npm modules and exploring the jspm project that converts npm modules into a format compatible with browsers.

However, I am encountering challenges, particularly with RxJS. RxJS version 6 suggests importing constructors and operators as follows:

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

Attempting to do this in the browser results in errors like:

Uncaught SyntaxError: The requested module '' does not provide an export named 'map'

To work around this, I can import the entire rxjs module and extract what is necessary:

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;

Nonetheless, this goes against the effort by the Rx team to optimize bundle size.

This issue extends beyond just RxJS. What steps should we take moving forward to achieve our goal of seamlessly transitioning our development javascript imports in the browser to meet bundler requirements?

Answer №1

Check out this quick and easy example starter stackblitz using rxjs:

To get started, make sure to include the rxjs js file in your script (you can grab it from a CDN)

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.1.0/rxjs.umd.js">

All functionalities are accessed through the rxjs namespace, here's a simple usage example:

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

Answer №2

To access the es6 module export syntax, you must navigate to the subfolder named _esm2015. Therefore, the following imports are necessary:

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

Unfortunately, simply installing rxjs with npm install rxjs@6 and then using import in the browser is not possible. This is because the distribution source lacks the file extension .js in the import statements: https://unpkg.com/@reactivex/[email protected]/dist/esm2015/index.js.

Currently, the browser requires file extensions for import (more information can be found here: 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';

An issue regarding this matter has been raised: https://github.com/ReactiveX/rxjs/issues/4416.

  • Side note: will redirect to

Currently, it is recommended to utilize or create your own bundle (such as using rollup as suggested by @Ovidiu Dolha).

Answer №3

var btn = document.querySelector("button");

var clickObs = rxjs.fromEvent(btn, "click");

var intervalObs = rxjs.interval(1000);

// intervalObs.subscribe((value) => {
//   console.log(value);
// });

clickObs.pipe(rxjs.switchMap(() => intervalObs)).subscribe((value) => console.log(value));
    <!DOCTYPE html>
    <html>

    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge'>
        <title>Page Title</title>
        <meta name='viewport' content='width=device-width, initial-scale=1'>
        <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62101a081122554c5a4c53">[email protected]</a>/dist/bundles/rxjs.umd.min.js"></script>
        <script defer src='main.js'></script>
    </head>

    <body>
        <button id="btn">
            Click Me
        </button>
    </body>

    </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking on the react router does not trigger any action

I'm currently developing a Pokemon list app similar to the one in this tutorial: https://www.youtube.com/watch?v=XehSJF85F38&t=5904s However, I've encountered an issue where my routes are not functioning properly, even though I followed the ...

When a JavaScript/jQuery open window popup triggers the onunload event after the about:blank page has been

Imagine you have a button that triggers a popup using window.open(): <button id = "my-button">Open window</button>​ You also want to detect when this popup window closes. To achieve this, you can use the following code: $('#my-button& ...

The jQuery autocomplete feature with typeahead suggestions fails to appear following a successful AJAX request

I am currently using typeahead.js to incorporate tags into my multiple input setup. The tagging function works as expected, however, I am facing an issue where the autocomplete suggestions are not appearing. Is there a solution to fix this problem? Despit ...

XMLHttpRequest problem: receiving status code 0 from both local and live server

I'm struggling to make this XMLHttpRequest work correctly. This is my first time using AJAX, so I'm not sure if I've formatted everything properly. I've searched all over the internet and found similar information and examples, but cert ...

Guide on obtaining an obscure style guideline in MS Edge using JavaScript

If you are looking to utilize the object-fit CSS rule, keep in mind that it is not supported in MSIE and MS Edge Browsers. While there are polyfills available for IE, none of them seem to work in Edge from my experience. For instance, the polyfill fitie b ...

Tips for updating a single parameter with vue router-link

I am facing an issue with my user list and calendar components. Whenever I click on a user link, I want only the selectedUser parameter in the URL to change while leaving all other parameters unchanged. Currently, when I click on the "Change date" link, i ...

Does the 'a' HTML tag secretly trigger window.location.assign?

Being relatively new to the online world, I have a simple question in mind. Imagine that I have a very basic a tag in my HTML: <a href="www.google.com"> Click me </a> What actually happens when I click on this link? Does the browser simply ...

Finding Corresponding Values in an Array with JavaScript

I am working with an array of objects that have a specific format: [ { "card_details": { "cardType": "gift" }, "merchant_details": { "merchantName": "Walter Heisenberg1", "timeZone": "+05:30", } }, { "card_detai ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

Passing data from input to Angular's $scope (filter)

I'm currently working on my first custom filter, and while the basic principle is functioning (it displays all the CDs of an artist from 7 and up), I'm encountering an issue where the filter doesn't update when I change the value. It consist ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...

Is there a way to retrieve time data from a different server through AJAX?

I am in need of obtaining time information from an online source, whether it be an NTP server, JSON time server, or simply an HTTP Header. The precision is not important to me, but the requirement is that I must get the time from an online source. Unfortun ...

Extract data from an ajax request in an AngularJS directive and send it to the controller

I am currently experimenting with integrating the jQuery fancy tree plugin with Angular. The source data for the tree is fetched through an ajax call within my controller. I am facing a challenge in passing this data to my directive in order to load the tr ...

The babelrc configuration alone is not enough to be used in conjunction with the babel --

Looking for help with my .babelrc configuration. { "presets": ["env"], "outDir":"target", "include":[ "src/**/*.js" ], "ignore": [] } When I use babel -w, I encounter the following error: --watch requires --out-file or --out-dir. --watch ...

send another response following the completion of the request.end()

I am facing challenges with writing the correct callback function. The situation involves a user making a request to "/city", which then triggers the server to make a request to a third-party service for data retrieval using http.request(). I successfully ...

Issue: Attempting to display array elements within a React Functional Component?

Encountering an issue while attempting to log array elements, receiving the error message: TypeError: Cannot read property '0' of undefined Interestingly, I am able to successfully log the project.tasks array object in the console. However, l ...

What could be causing this code to fail in making changes to the HTML document?

I tried incorporating the following code into my website: $('.feed-item').append('<p> This is paragraph element. </p>'); You can view it on this page: Test Unfortunately, the code does not seem to be functioning properly. ...

Thumbnail Reactive Player

I have been using react-player for my video needs and it seems to be getting the job done. However, I am facing an issue where I need to retrieve thumbnails for the videos. Does anyone have any suggestions on how I could go about this? If there are better ...

The toggle function for the hamburger icon is currently malfunctioning

I am facing an issue with the hamburger icon on my website. The toggle functionality associated with it is not working properly. Even though I have a class named change-1 that should be toggled upon clicking the icon, it is not happening. There are no erro ...

Troubles with data tables, pagination, and selecting rows

My application features a datatable with pagination. When a user selects a row in the table, a report is displayed below it that can be edited. If the user attempts to select another row without saving any pending edits, they are given a warning and the op ...