1

I have a very simple application written in TypeScript:

src/index.ts

import * as http from "http";

const server = http.createServer((request, response) =>
{
    response.end("Hello, World");
});

server.listen(3000);

Then my TypeScript configuration:

tsconfig.json

{
    "compilerOptions": {
        // Output options
        "target": "es5",
        "lib": [
            "es2016"
        ],
        "module": "commonjs",
        "outDir": "./build",
    }
}

I can build my code using npx tsc and then run it using node ./build/index.js, and upon visiting http://localhost:3000 in a browser I see the message "Hello, World" -- all good so far

Now using npx tsc -w I can watch the files to see if they change and re-compile them when this happens. This command run "forever" (until stopped) so it prevents me from running node ./output/index.js in the same terminal. Using multiple terminal windows or a terminal multiplexer I can pretty trivially run node ./output/index.js, but this file won't get re-run if my code is re-compiled. This means that if I change the string "Hello, World" to "Hello, Steven" I won't see the change until I manually stop my server and restart it

Is there a way to watch my TypeScript files like this and run the output so that the output is stopped and re-run when my code changes?

stevendesu
  • 13,153
  • 13
  • 76
  • 146
  • 1
    Closely related: [*How to auto-reload files in Node.js?*](https://stackoverflow.com/questions/1972242/how-to-auto-reload-files-in-node-js) – T.J. Crowder Apr 09 '20 at 18:23
  • Closely related: [*How to watch and reload ts-node when TypeScript files change*](https://stackoverflow.com/questions/37979489/how-to-watch-and-reload-ts-node-when-typescript-files-change) and [*nodemon watches onjy JavaScript files not TypeScript*](https://stackoverflow.com/questions/48565505/nodemon-watches-onjy-javascript-files-not-typescript) – T.J. Crowder Apr 09 '20 at 18:24
  • 2
    I won't vote to close because I have a dupehammer and don't want to use it (if I did, I'd point to [this](https://stackoverflow.com/questions/48565505/nodemon-watches-onjy-javascript-files-not-typescript)), but it looks like the answer is `nodemon` + `ts-node` with a bit of config. – T.J. Crowder Apr 09 '20 at 18:26

1 Answers1

2

You could run tsc and nodemon at the same time:

npx tsc -w & npx nodemon build

or use nodemon with ts-node:

npx nodemon -x ts-node -e ts src
# to run even if there are TS errors:
npx nodemon -x 'ts-node --log-error' -e ts src

or just use ts-node-dev:

npx ts-node-dev src
cherryblossom
  • 5,523
  • 2
  • 15
  • 39