ts-nodeを使ってlocalでTypescriptを楽に実行できるようにする
はじめに
この記事は、Typescript(.tsファイル)を直接実行できるようにする環境構築のメモです。
前提としてnodeとnpmはインストール済みとしています。
今回はnpxを使用しているのでインストールしていない場合は、インストールしておきましょう。
$ npm install -g npx
プロジェクトディレクトリの作成
$ mkdir typescript-node $ cd typescript-node
package.jsonの生成~typescriptの追加
npm init -y npm install typescript npm install -D @types/node
tsconfig.jsonの作成
$ touch tsconfig.json
or
$ npx tsc --init
tsconfig.json
{ "compilerOptions": { "target": "es6", "module": "commonjs", "sourceMap": true, "outDir": "./dist", "strict": true, "esModuleInterop": true }, "include": [ "src/**/*" ] }
Typescriptファイルの作成
$ mkdir src $ touch src/index.ts
src/index.ts
function hello(message: string): string { return `Hello, ${message}!` } console.log(hello('World'))
typescript
パッケージに同梱されているtsc
コマンドを実行しましょう。
$ npx tsc
するとdist
ディレクトリの中にindex.js
とindex.js.map
が生成されます。
$ ls dist
index.js index.js.map
生成されたindex.js
を実行してみましょう。
$ node dist/index.js Hello, World!
ts-nodeを導入して手間を減らす
毎回.ts
ファイルを編集してtsc
コマンドでコンパイルしてnode
で実行するのは手間もかかる上に面倒なのでtsc -> node
の実行を自動で行ってくれるts-node
を導入しましょう。
$ npm install -D ts-node
npm install
が終了したらts-node
コマンドを実行してみましょう。
$ npx ts-node src/index.ts Hello, World!
package.jsonのnpm-scriptにdevを追加
{ ... "scripts": { "dev": "ts-node src/index.ts", "test": "echo \"Error: no test specified\" && exit 1" }, ... }
早速実行してみましょう。
$ npm run dev > typescript-node@1.0.0 dev /Users/<username>/typescript-node > ts-node src/index.ts Hello, World!