Express を TypeScript で作成していて開発中は nodemon で ts-node を使って変更を監視してホットリロードさせたかったのですが、ファイル変更が watch されない問題にハマったのでメモ。
構成
/project_root |- /src | |- index.ts |- package.json |- nodemon.json # nodemon の設定 |- tsconfig.json
環境
node: v12.18.4
npm: v6.14.6
nodemon: ^2.0.4
ts-node: ^9.0.0
typescript: ^4.0.3
nodemon.json
{ "restartable": "rs", // process.env に渡す値 "env": { "NODE_ENV": "dev" }, // 監視するディレクトリ "watch": [ "src" ], "ignore": [ "tests/**/*.ts" ], // nodemon 起動時に実行されるファイル "exec": "ts-node ./src/index.ts" }
npm script (package.json)
"scripts": { "dev": "nodemon -L" }
この状態で $ npm run dev
コマンドを実行すれば /src
にある ts ファイルを監視してホットリロードできるはずだったのですが、 /src/index.ts
を変更してもコンソールには何も表示されるブラウザも更新がされない… どうやら watch が正しくされてないようでした。nodemon.json
の watch を src/**/*.ts
のようにしても watch されない状態のまま…
ext
プロパティに監視対象のファイルを指定する必要があった
nodemon はデフォルトでは .js
, .mjs
, .coffee
, .litcoffee
, .json
だけが監視対象になっているようで、TypeScript のファイルを変更しても watch 対象ではないから動作していなかった。ということのようでした。
nodemon.json
に下記設定を追加
{ "restartable": "rs", "env": { "NODE_ENV": "dev" }, "watch": [ "src" ], // ts, json を監視対象にする "ext": "js, ts, json", "ignore": [ "tests/**/*.ts" ], "exec": "ts-node ./src/index.ts" }
Specifying extension watch list
By default, nodemon looks for files with the.js
,.mjs
,.coffee
,.litcoffee
, and.json
extensions. If you use the--exec
option and monitorapp.py
nodemon will monitor files with the extension of.py
. However, you can specify your own list with the-e
(or--ext
) switch like so:$ nodemon -e js,pugcf Typescript + Express + Webpackで作る、node.jsサーバー環境構築入門 - Qiita
これで $ npm run dev
で ts ファイルを監視してホットリロードされる開発環境が整いました!
やったね!
[参考]
- Typescript + Express + Webpackで作る、node.jsサーバー環境構築入門 - Qiita
- GitHub - remy/nodemon: Monitor for any changes in your node.js application and automatically restart the server - perfect for development
- ts-node で TypeScript + node をサクッと実行する - Qiita

- 作者:Mario Casciaro,Luciano Mammino
- 発売日: 2019/05/18
- メディア: 単行本(ソフトカバー)

- アーティスト:さよならポニーテール
- 発売日: 2013/03/06
- メディア: CD