LoginSignup
15
13

More than 3 years have passed since last update.

nodeをTypeScriptで利用する

Posted at

フロントエンドはだいたいTypescriptに書くのが普通になってきたので、次はバックエンドも。

準備

まずは準備。

作業場の作成

mkdir ts-test
cd ts-test
npm init -y

必要なモジュールインストール

必要なモジュールをインストールします。ポイントはts-nodeのインストールです。
ts-nodeはjsのトランスパイルなしにtsコードを実行してくれます。

npm install -D typescript
npm install -D @types/node
npx tsc --init

npm install -D ts-node

-Dは--save-devと同義。tsc --initでtsconfig.jsonも生成しておきます。

実装

まずファイルを作ります。

touch index.ts

実装します。簡単なコードです。

index.ts
const hello = (message: string): void => {
    console.log("message is " + message);
}

hello("hoge");

実行

ts-nodeで実行します。

npx ts-node index.ts

message is hoge

npxは./node_modules/.bin/ts-nodeと同義です(そこになければ一時的にインストールされ実行されます)

おまけ

一度jsにトランスパイルしてから実行

ts-nodeがなければ一度、tscでトランスパイルしてindex.jsを生成してから実行します。

npx tsc index.ts
node index.js

message is hoge
15
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13