Search code examples
node.jstypescripttsc

How to watch and re-run TypeScript on change?


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?


Solution

  • 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