カテゴリー
 【Rxjs基礎講座】Typescript & Babelでrxjsを手軽に試せる砂場(sandbox)を構築してみよう  
※ 当ページには【広告/PR】を含む場合があります。
2020/08/26
 2022/10/05 
「Rxjs」Observableそんなとき、サクッと
rxjsどうせなら
typescriptrxjsECMAScriptbabel今回は
rxjsrxjs砂場Requirements
言わすもがな
nodejsnpmまた、この記事内でパッケージマネージャは
yarnnpm参考までに現在の著者の手元の環境では、以下のようになっております。
            $ node --version
v12.13.1
$ npm --version
6.12.1
$ yarn --version
1.19.1
        rxjsとtypescriptとbabelのインストール
今回は
tsctypescriptjavascriptbabel-node好みにも依りますが、コマンドラインですぐに叩けるように、以下のようにグローバルインストールしておきます。
            $ npm i -g typescript @babel/core @babel/node
        rxjsのインストール
それでは
rxjsまずは
package.json            $ npm init -y
        とすると、
package.json            $ touch package.json
        として、中身を以下の内容で編集します。
            {
    "name": "nxjs-sandbox",
    "version": "0.0.1",
    "description": "To make a test for rxjs easier",
    "main": "dist/index.js",
    "types": "dist/index.d.ts",
    "private": true,
    "scripts": {
        "build": "tsc"
    }
}
        編集し終わったら、
rxjs            $ yarn add @types/node -D #tsでnodejsを使うための型定義セット(おまじない)
$ yarn add rxjs -S
        これでプロジェクト内で
rxjstscの設定
次にtscのコンパイル設定ファイルを作成します。
            $ tsc --init
        としても
tsconfig.jsonもちろん空の
tsconfig.json今回は以下の内容で設定します。
            {
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "declaration": true,
        "sourceMap": true,
        "outDir": "./dist",
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true
    },
    "include": [
        "./index.ts"
    ],
    "compileOnSave": false
}
        今回は簡単に、ルートディレクトリにある
index.tsdist慣れてきたら、適宜書き換えてみて遊んでみてください。
rxjsを簡単にテストしてみる
それでは
rxjsルートディレクトリに
index.ts            $ touch index.ts
        なおこの時点で、プロジェクト構造は
node_modules            $ tree -I node_modules
.
├── index.ts
├── package.json
├── tsconfig.json
└── yarn.lock
        それでは
index.ts            import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';
const range$ = () => {
    range(1, 100).pipe(
        filter(x => x % 2 === 1),
        map(x => x + x)
    ).subscribe(x => console.log(x));
};
range$();
        内容は1から100までの整数を、奇数だけフィルターして、その奇数どうしを足したものを出力しております。
tscビルド
それではビルドしてみます。
            $ tsc
        なおここでは、
tsconfig.jsonこうすることでコマンドでファイルを引数で指定しなくても勝手にファイルを見つけてビルドしてくれます。
正常にビルドできたら、
dist            $ tree -I node_modules
.
├── dist
│   ├── index.d.ts
│   ├── index.js
│   └── index.js.map
├── index.ts
├── package.json
├── tsconfig.json
└── yarn.lock
        jsコードの実行
それでは
rxjs            $ babel-node dist/index.js
2
6
#...中略
194
198
Done in 0.49s.
        問題がなければ、いい感じで
rxjsまとめ
以上、非常にシンプルな手順で
rxjsもちろん
typescriptとはいえ、まだ今回程度のソースコードだと、
babel-nodenodeこれからまだまだ
typscript&rxjsbabel