Is there a way to use npm scripts to run tsc -watch && nodemon --watch?

I'm looking for a way to use npm scripts to run tsc --watch && nodemon --watch at the same time. I can run these commands independently, but when I want run both of them, only the first one is executed. eg:

"scripts": {    
    "runDeb": "set NODE_ENV=development&& tsc --watch && nodemon --watch"
  }

tsc --watch is executed but nodemon is never called, and vice versa.


I think what you want is something like this (my current setup):

"scripts": {
    "compile": "tsc && node app.js",
    "dev": "./node_modules/nodemon/bin/nodemon.js -e ts  --exec \"npm run compile\""
}

I created two scripts "compile" and "dev". To start developing you simply run npm run dev which starts nodemon and makes it watch .ts files (using the -e flag). Then, every time a .ts file changes nodemon will exec the compile task which basically compiles and runs the node app.

While using concurrently is a good option, my setup guarantees that tsc's work is done before attempting to execute the resulting .js files.


I have been using AlterX's solution for a while now and it has worked perfectly, but I have found it to be rather slow. Instead, I am now using tsc-watch. It makes tsc use incremental compilation similar to the -w flag, making the restart of the application much faster.

It's as easy as putting something similar to this in your package.json:

"scripts": {
  "start": "tsc-watch --onSuccess \"node .\""
}

Try to add this to your package.json:

"scripts": {
  "start": "concurrently --kill-others \"tsc -w\" \"nodemon dist/app.js\"",
}

And also add this npm packages (concurrently, nodemon, typescript) to your package.json:

"devDependencies": {
  "concurrently": "^2.2.0",
  "typescript": "^1.8.10",
  "nodemon": "^1.9.2",
}

What's going on

The problem is there are two watchers here on all the files. One is tsc -w and one is nodemon.

When a change to a .ts file is made, tsc detects that, compiles it, and creates the .js version in your destination folder.

Now from the Nodemon's perspective, it detects two changes (at least) -- one for .ts and one for .js. On the first change it restarts itself, but on the second change it doesn't know that another "start" is going on already, so it tries to restart again and it fails. To me it's a nodemon bug -- see https://github.com/remy/nodemon/issues/763.

Solutions

1) Use tsc-watch --onSuccess

tsc-watch has --onSuccess which you can put node on there. This way you will have only one watcher.

2) Delay nodemon

You can easily delay nodemon restarts (See --delay). It requires the least set up change.

3) Have nodemon only monitor destination folder of TSC

I couldn't get it to set up, but this way nodemon will detect only one change hopefully. It might cause problems in future or when tsc generates multiple files.