Search code examples
typescriptrxjses6-module-loader

Typescript with rxjs


Im currently working on a typescript project without any module loaders.

Now I am trying to integrate rxjs, in my project. But i get everytime the error ReferenceError: exports is not defined. Is it necessary to use a module loader, and if yes could u help me on setting it up? Im currently compiling the ts file with tsc -w

Main.ts

const mock = of('Hello');
mock.subscribe(res => console.log(res));

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>HM</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="assets/hm-logo.png">
    <link rel="stylesheet" type="text/css" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<script src="./main.js"></script>
</body>
</html>

Solution

  • Thanks to @toskv I managed to integrate rxjs to typescript without any module loaders. To accomplish this I needed to take consideration to following steps:

    1.Step

    Add the cdn link to the root HTML (within the head tag) like follows:

    <script src="https://unpkg.com/rxjs@6.3.3/bundles/rxjs.umd.min.js"></script>
    

    2.Step

    Add a rxjs.d.ts file with a global variable:

    declare var rxjs;
    

    3.Step

    Include the rxjs.d.ts file in the tsconfig.json file like:

      "include": [
        "src/**/*",
        "rxjs.d.ts"
      ]
    

    4.Step

    Now you can use rxjs in your ts file like:

    const { Observable, Subject, ReplaySubject, from, of, range } = rxjs;
    const { map, filter, switchMap } = rxjs.operators;
    
    range(1, 200)
        .pipe(filter(x => x % 2 === 1), map(x => x + x))
        .subscribe(x => console.log(x));