LoginSignup
1
0

More than 1 year has passed since last update.

Typescriptとexpress.jsの環境設定

Posted at

目標

  • expressでtypescriptを導入する
  • tyepescriptでバックエンドを書く

目的

  • typescriptの学習
  • typescriptを使った環境設定

手順

1.環境の確認

$ node -v
v16.5.0

$ npm -v
7.19.1

2.ワーキングディレクトリーを作成

$ mkdir project_name
$ cd project_name
$ npm init

3.typescriptのインストールと設定

$ npm install -g typescript
$ tsc --init

tsconfig.json でnodeを使えるようにする

// コメントアウトをはずす
"moduleResolution": "node",

"outDir": "./dist", // 出力先を指定する
"rootDir": "./src", //もとのファイルを指定する

4.expressをインストールする

expressをtypescriptで使うためのライブラリーも一緒にダウンロードする

$ npm install --save express
$ npm install -D @types/express
// nodeをtypescriptで使うためのライブラリーも追加
$ npm install -D @types/node

index.ts にサーバーを立上げるコードを書く

import express, { Request, Response, NextFunction } from 'express'

const app = express()

// /にアクセスが有るときの処理
app.get('/', (req: Request, res: Response) => {
  res.json('Hello World')
})

// エラー処理
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  res.status(500).json({ message: err.message })
})

app.listen(3000)

5.ts-nodeを使って開発の効率を上げる

// ホットリロードをするためのライブラリーも追加
$ npm install -D nodemon ts-node

現在はts→js→nodeになっている。

それをts→nodeとできるようにts-nodeをライブラリーを追加する

package.jsonに以下のコードを追加して自動で更新されるようにする

"scripts": {
    "start": "nodemon --watch './**/*.ts' --exec ts-node src/index.ts"
  },

これでターミナルに npm startとホットリロードができるようになる。

[localhost:3000](http://localhost:3000) にアクセスすると

Hello Wold

がかえってくる。

参考

TypeScript + Node.js プロジェクトのはじめかた2020 - Qiita

TypeScript - Use Nodemon to Restart Your Server on Changes

1
0
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
1
0