How to watch and reload ts-node when TypeScript fi

2019-01-12 22:01发布

问题:

I'm trying to run a dev server with TypeScript and an Angular application without transpiling ts files every time. I found that I can do the running with ts-node but I want also to watch .ts files and reload the app/server as I would do with something like gulp watch.

回答1:

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


回答2:

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.



回答3:

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.ts"



回答4:

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



回答5:

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