UPDATE

See "Run TypeScript in Node without extensions" as of Dec 10, 2024. (5 months later)


You might have heard that Node now has watch mode. It watches the files you're saving and re-runs the node command automatically. Example:


// example.js

function c2f(c) {
  return (c * 9) / 5 + 32;
}
console.log(c2f(0));

Now, run it like this:

❯ node --watch example.js
32
Completed running 'example.js'

Edit that example.js and the terminal will look like this:

Restarting 'example.js'
32
Completed running 'example.js'

(even if the file didn't change. I.e. you just hit Cmd-S to save)

Now, node doesn't understand TypeScript natively, yet. So what are you to do: Use @swc-node/register! (see npmjs here)
You'll need to have a package.json already or else use globally installed versions.

Example, using npm:


npm init -y 
npm install -D typescript @swc-node/register
npx tsc --init

Now, using:


// example.ts

function c2f(c: number) {
  return (c * 9) / 5 + 32;
}
console.log(c2f(123));

You can run it like this:


❯ node --watch --require @swc-node/register example.ts
253.4
Completed running 'example.ts'

Comments

Your email will never ever be published.

Related posts