How to watch and reload ts-node when TypeScript files change
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
You can now simply npm install --save-dev ts-node nodemon
and then run nodemon
with a .ts
file and it will Just Work:
nodemon app.ts
Previous versions:
I was struggling with the same thing for my development environment until I noticed that nodemon
's API allows us to change its default behaviour in order to execute a custom command.
For example, for the most recent version of nodemon
:
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "ts-node src/index.ts"
Or create a nodemon.json
file with the following content:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/index.ts" // or "npx ts-node src/index.ts"
}
and then run nodemon
with no arguments.
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!
And with even older versions of nodemon
:
nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts
Or even better: externalize nodemon's config to a nodemon.json
file with the following content, and then just run nodemon
, as Sandokan suggested:
{
"watch": ["src/**/*.ts"],
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./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.
This works for me:
nodemon src/index.ts
Apparently thanks to since this pull request: https://github.com/remy/nodemon/pull/1552