Thursday, August 11, 2022

Node.js + Express + TypeScript (ts-node reloaded)

This is a short follow up to one of my previous posts, the Node.js + Express + TypeScript where a tiny tutorial on writing node.js node with TypeScript was discussed.
This time I'd like to introduce the ts-node which basically wraps the TypeScript execution in a single pipeline so that there's no need to precompile the TypeScript to JavaScript.
One of ways to use the ts-node is to install it globally and run the TypeScript code with
ts-node app.ts
Note only that the tsconfig.json has to be present, just to configure TypeScript options.
However, to also be able to debug the TypeScript from the Visual Studio Code and still use the ts-node to execute the code, install the ts-node locally and create a .vscode/launch.json section
{
    "name": "ts-node",
    "type": "node",
    "request": "launch",
    "args": ["${workspaceFolder}\\app.ts"],
    "runtimeArgs": ["-r", "ts-node/register"],
    "cwd": "${workspaceRoot}",
}
A tiny code to test this
// app.ts
import * as http from 'http';
import express, { Express, Request, Response } from 'express';

var app: Express = express();

app.get('/', (req: Request, res: Response) => {
    res.write('hello world');
    res.end();
});

var server = http.createServer(app)

server.listen(3000);

console.log( 'started' );

No comments: