Monday, April 25, 2022

Node.js + Express + TypeScript

The Node.js + Express + Javascript is a great platform and this short tutorial shows how to add TypeScript to the picture.

Start with installing TypeScript compiler globally

npm install typescript -g
so that whenever you invoke tsc from the command line, the compiler follows your tsconfig.json and does its job. Then add the tsconfig.json
{
    "compilerOptions": {
        "lib": [
            "es2021", "DOM"
        ],
        "module": "commonjs",
        "target": "es2021",
        "strict": true,
        "esModuleInterop": true,
        "sourceMap": true                
    }
}
Note that we specifically ask the module subsystem to translate TypeScript's export/imports into node.js commonjs modules. We also turn on the esModuleInterop flag for better node.js compatibility.

Now install some typings for node and express (other typings should possibly also be installed, depending on what packages you are going to use.

npm i --save-dev @types/node
npm i --save-dev @types/express

Create the app.ts file, which will be the starting point of the app and add .vscode/launch.json with

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\\app.ts",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}
Note how the entry point (program) is set up here. Because the Typescript compiler will generate source maps, you would be able to run&debug the Typescript code.

Writing Typescript is easy now. Create an example express app

import * as http from 'http';
import express from 'express';

var app = express();

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

var server = http.createServer(app)

server.listen(3000);

console.log( 'started' );
Note how express is imported and how a library module (http) is imported - in both cases, there's the full intellisense support in VS Code as well as the support from the Typescript compiler.

To compile the code just invoke

tsc
once. To run the compiler in the watch mode:
tsc --watch

To show how TS modules work, create a simple module, m.ts with

class Example {
    DoWork( s: string ) : string {
        return s + ' from Example';
    }
}

export default Example;
and import it in the app.ts
import * as http from 'http';
import express from 'express';
import Example from './m';

var app = express();

app.get('/', (req, res) => {

    let e = new Example();

    res.write(e.DoWork('hello world'));
    res.end();
});

var server = http.createServer(app)

server.listen(3000);

console.log( 'started' );
Note how m.ts is compiled to m.js and also note how m.js is imported in the app.js (compiled from app.ts).

No comments: