27

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'",

6 Answers 6

47

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"
}
0
22

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

1
  • 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.
    Commented Jan 6, 2022 at 14:07
13

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

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.

1
  • this is the correct answer! thank you. Commented Nov 29, 2021 at 21:54
5

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
0

I'm using nodemon + concurrently libraries:

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

build script:

"build": "tsc"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.