25

I want my typescript files to be compiled on every file saving with the command tsc.

How do I combine the tsc command with the command that nodemon runs in the build:live script

"scripts": {
    "start": "npm run build:live",
    "build:live": "nodemon --watch '*.ts' --exec 'ts-node' app.ts",
 }

this script causes nodemon to call itself twice or three times:

"build:live": "nodemon --watch '*.ts' --exec 'ts-node app.ts & tsc'",
Jeroen
  • 1,168
  • 1
  • 12
  • 24
SwiftiSwift
  • 7,528
  • 9
  • 56
  • 96

6 Answers6

44

Nodemon will detect and run .ts files with ts-node automatically now. It will actually run .py and .rb files with python and ruby too btw and you can give it a custom --exec for others. Here's a link to the relevant code within nodemon.

So the following should be fine:

"scripts": {
  "dev": "nodemon app.ts"
}
kjs3
  • 5,758
  • 8
  • 34
  • 49
20

This looks like it will achieve what you're looking for:

"start": "tsc-watch --project . --outDir ./dist --onSuccess \"nodemon ./dist/bin/www.js\""

Source: https://github.com/Microsoft/TypeScript/issues/12996#issuecomment-349277673

Zachary
  • 486
  • 4
  • 6
  • 2
    This solved my exact problem. I wanted the TS to transpile, make sure the transpilation was successful and then run a specific file in dist. Thank you! – Michael F. Jan 06 '22 at 14:07
11

With the current answer you might run into issues using ES modules. No need for nodemon when you're using tsc-watch. It makes use of incremental compilation, making the restart of your application much faster.

I found the following to work best:

"start": "tsc-watch --onSuccess \"node ./dist/app.js\""

The outDir can be defined in your tsconfig

Vitalynx
  • 946
  • 1
  • 8
  • 17
6

As of TypeScript 3.8+, you can now just use:

tsc --watch

https://www.typescriptlang.org/docs/handbook/configuring-watch.html

You could then use nodemon on the compiled code, e.g. nodemon dist/app.js.

Peter W
  • 952
  • 8
  • 18
4

You can create a nodemon.json in your project root directory and add the following code inside that:

{
 "ext": "*.ts",
 "exec": "tsc && ts-node app.ts"
}

And update your scripts like following:

"scripts": {
   "start": "npm run build:live",
   "build:live": "nodemon",
}

What happens is that nodemon will check all the files with the extension ".ts" and starts tsc and then ts-node.

0

I'm using nodemon + concurrently libraries:

"watch": "concurrently \"npm run build -- --watch\" \"nodemon --watch '**/*' --exec npm run start\"",

build script:

"build": "tsc"
jawn
  • 851
  • 7
  • 10