How to watch and reload ts-node when TypeScript files change

HeberLZ

I was struggling with the same thing for my development environment until i noticed that nodemon's api allows us to change it's default behaviour in order to execute a custom command. An example of this would be like follows:

nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts

Or even better and externalize nodemon's config as Sandokan sugested to a nodemon.json file with the following content, and then just run nodemon:

{ "watch": ["src/**/*.ts"], "ignore": ["src/**/*.spec.ts"], "exec": "ts-node ./index.ts" }

By virtue of doing this you'll be able to live-reload a ts-node process without having to worry about the underlying implementation.

Cheers!

Updated for most recent version of nodemon:

Create a nodemon.json file with the following content.

{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "ts-node ./src/index.ts"
}

Here's an alternative to the HeberLZ's answer, using npm scripts.

My package.json:

  "scripts": {
    "watch": "nodemon -e ts -w ./src -x npm run watch:serve",
    "watch:serve": "ts-node --inspect src/index.ts"
  },
  • -e flag sets the extenstions to look for,
  • -w sets the watched directory,
  • -x executes the script.

--inspect in the watch:serve script is actually a node.js flag, it just enables debugging protocol.

I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev https://github.com/whitecolor/ts-node-dev

Just run ts-node-dev src/index.ts

gilamran

Specifically for this issue I've created the tsc-watch library. you can find it on npm.

Obvious use case would be:

tsc-watch server.ts --outDir ./dist --onSuccess "node ./dist/server.js"

Add "watch": "nodemon --exec ts-node -- ./src/index.ts" to scripts section of your package.json.

you could use ts-node-dev

It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts.

Install

yarn add ts-node-dev --dev

and your package.json could be like this

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "tsc": "tsc",
  "dev": "ts-node-dev --respawn --transpileOnly ./src/index.ts",
  "prod": "tsc && node ./build/index.js"
}

i did with

"start": "nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts"

and yarn start.. ts-node not like 'ts-node'

I use tsmon https://www.npmjs.com/package/tsmon it deep integrated with typescript and provide incremental transpile and reload feature.

I was using ts-node-dev until one day I noticed it can not detect the changes on interfaces.

Install

npm install tsmon

Go to your typescript project folder

tsmon [you .ts file]