カテゴリー
【Rxjs基礎講座】Typescript & Babelでrxjsを手軽に試せる砂場(sandbox)を構築してみよう
※ 当ページには【広告/PR】を含む場合があります。
2020/08/26
2022/10/05
「Rxjs」
Observable
そんなとき、サクッと
rxjs
どうせなら
typescript
rxjs
ECMAScript
babel
今回は
rxjs
rxjs砂場
Requirements
言わすもがな
nodejs
npm
また、この記事内でパッケージマネージャは
yarn
npm
参考までに現在の著者の手元の環境では、以下のようになっております。
$ node --version
v12.13.1
$ npm --version
6.12.1
$ yarn --version
1.19.1
rxjsとtypescriptとbabelのインストール
今回は
tsc
typescript
javascript
babel-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
これでプロジェクト内で
rxjs
tscの設定
次に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.ts
dist
慣れてきたら、適宜書き換えてみて遊んでみてください。
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-node
node
これからまだまだ
typscript&rxjs
babel
記事を書いた人
ナンデモ系エンジニア
主にAngularでフロントエンド開発することが多いです。 開発環境はLinuxメインで進めているので、シェルコマンドも多用しております。 コツコツとプログラミングするのが好きな人間です。
カテゴリー